我有以下Devise注册表(省略了无关标记):
<%= 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 %>
此表单吐出以下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>
然后,我的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
当我提交表单时,我得到“PaidAccount(#2163736620)预期,获得ActionController ::参数(#2173083140)”。
我也尝试过以下不会出错的内容,但它也没有创建记录:
u.permit(
:email,
:password,
:paid_account => []
)
我做错了什么?
答案 0 :(得分:0)
显示您的两个模型(我相信User
和PaidAccount
)会有很大帮助。无论如何,假设User
与PaidAccount
具有一对一的关系,代码应该如下所示:
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
查看您的日志,了解表单值的提交方式。 StrongPameters gem和Active Record's Nested Attributes的文档也应该有所帮助。