我正在使用 Devise 和 Rails 4 开发一个网络应用程序。我有一个User我用 2 个额外的表单字段扩展了该模型,这样当用户注册时,他还可以提交他的名字/姓氏。 (基于http://blog.12spokes.com/web-design-development/adding-custom-fields-to-your-devise-user-model-in-rails-4/ http://blog.12spokes.com/web-design-development/adding-custom-fields-to-your-devise-user-model-in-rails-4/)。我现在想添加一个机构模型。这个型号has_many:用户和用户属于:机构。我希望能够注册机构名称在同一张表格上我注册了用户。我知道我需要一个nested_attribute机构模型,因为这是父级,我稍后会展示它。当我尝试注册用户时,我进入控制台:不允许的参数:机构.
我的提示是,我无法根据我的子类(用户)更新我的父类(机构)。这个问题可能有解决办法吗?或者有人经历过类似的事情吗?
class Institutions < ActiveRecord::Base
has_many :users,
accepts_nested_attributes_for :users
end
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :institution
end
注册/new.html.erb这里我有嵌套的形式
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
.
.
<%= f.fields_for :institutions do |i| %>
<p><%= i.label :name %><br />
<%= i.text_field :institutions_attr %></p>
<% end %>
根据我之前链接的教程,我创建了一个新的用户::参数消毒器它继承自Devise::参数消毒剂并覆盖sign_up
方法如下:
lib/user_sanitizer.rb
private
def sign_up
default_params.permit(:first_name, :last_name ,:email, :password, :password_confirmation, :current_password, institutions_attributes: [:id, :name])
end
最后,我的应用程序控制器.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
protected
def devise_parameter_sanitizer
if resource_class == User
User::ParameterSanitizer.new(User, :user, params)
else
super
end
end
end
感谢您的阅读!
控制台参数输出:
{"utf8"=>"✓",
"authenticity_token"=>"JKuN6K5l0iwFsj/25B7GKDj7WEHR4DO3oaVyGxGJKvU=",
"user"=>{"email"=>"[email protected] /cdn-cgi/l/email-protection",
"first_name"=>"abc",
"last_name"=>"xyz",
"institutions"=>{"name"=>"Government"},
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"},
"commit"=>"Sign up"}
EDIT
根据建议,我添加了
params.require(resource_name).permit( :email, :first_name, :last_name, institution: [:name], :password, :password_confirmation ) and I get an *error syntax error, unexpected ',', expecting => ...nstitution: [:name], :password, :password_confirmation )*
但是,如果我重新编辑
params.require(resource_name).permit( :email, :first_name, :last_name, :password, :password_confirmation, institution: [:name] )
我没有收到任何语法错误,但收到了 Unpermitedparameters:Institutions in the Request。
我相信发生这种情况是因为用户是机构的子级。但是,我一直无法找到解决此问题的方法。