Confused about strong parameters with Devise

。_饼干妹妹 提交于 2019-12-24 23:19:02

问题


I have the following Devise registration form (with irrelevant markup omitted):

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { id: "payment-form" }) do |f| %>
  <%= f.fields_for resource.paid_account do |pa| %>
    <%= pa.collection_select :account_plan_id, @account_plans, :id, :name_with_price %>
  <% end %>
<% end %>

This form spits out the following HTML:

<select id="user_paid_account_account_plan_id" name="user[paid_account][account_plan_id]">
  <option value="2">Lite ($10.00/mo)</option>
  <option value="3">Professional ($20.00/mo)</option>
  <option value="4">Plus ($30.00/mo)</option>
</select>

I then have the following code in my ApplicationController:

class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(
        :email,
        :password,
        :paid_account => :account_plan_id # <-- THIS IS PROBABLY WRONG
      )
    end
  end
end

When I submit my form I get "PaidAccount(#2163736620) expected, got ActionController::Parameters(#2173083140)".

I've also tried the following which doesn't give an error, but it also doesn't create a record:

  u.permit(
    :email,
    :password,
    :paid_account => []
  )

What am I doing wrong?


回答1:


Showing your two models (User and PaidAccount, I believe) would help a great deal. Regardless, assuming User has a one-to-one relationship with PaidAccount, the code should probably look like this:

class User < ActiveRecord::Base
  has_one :paid_account

  accepts_nested_attributes_for :paid_account
end

class PaidAcount < ActiveRecord::Base
  belongs_to :user
end

class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(
        :email,
        :password,
        :paid_account_attributes => :account_plan_id
      )
    end
  end
end

Look at your logs to see how the form values are being submitted. The docs of the StrongPameters gem and Active Record's Nested Attributes should also be helpful.



来源:https://stackoverflow.com/questions/21888960/confused-about-strong-parameters-with-devise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!