未允许的参数:profile(NestedAttributes) – RAILS 4

这个问题多次被其他用户询问,但仍未解决我的问题。 我的rails应用程序出现问题,出现错误“未允许的参数:配置文件”。

user_controller.rb

class Admin::UsersController  (1)" if @user.update(user_params) redirect_to edit_admin_user_path, notice: "#{@user.profile.full_name} account has been updated." else render 'edit' end end private def set_user @user = User.find(params[:id]) end def user_params params.require(:user).permit(:id, :username, :email, profile_attributes: [:user_id, :full_name]) end end 

edit.html.erb

  

"form-control" %>

"form-control" %>
"btn btn-primary" %>

User.rb

 class User  { :case_sensitive => false } end 

Profile.rb

 class Profile < ActiveRecord::Base belongs_to :user validates_presence_of :user_id validates_presence_of :full_name end 

development.log

 Started PATCH "/master/users/7" for 127.0.0.1 at 2014-09-10 23:18:26 +0800 Parameters: {"utf8"=>"✓", "authenticity_token"=>"23oUfOBaYAmcrfhW3R11F1x53lJAT760Shv0HqkmEzw=", "user"=>{"username"=>"lisa", "profile"=>{"full_name"=>"Evalisa Andriaasdasda"}}, "commit"=>"Save", "id"=>"7"} [1m[35mUser Load (0.3ms)[0m SELECT `users`.* FROM `users` WHERE `users`.`id` = 7 LIMIT 1 [1m[36mUser Load (0.3ms)[0m [1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 6 ORDER BY `users`.`id` ASC LIMIT 1[0m Unpermitted parameters: profile [1m[35m (0.2ms)[0m BEGIN [1m[36mUser Exists (0.4ms)[0m [1mSELECT 1 AS one FROM `users` WHERE (`users`.`username` = 'lisa' AND `users`.`id` != 7) LIMIT 1[0m [1m[35m (0.2ms)[0m COMMIT [1m[36mProfile Load (0.4ms)[0m [1mSELECT `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` = 7 LIMIT 1[0m 

我真的不知道哪里出错了。 请帮忙。

提前致谢!

更新user_params方法以包含配置文件对象中的所有属性。 您缺少id因此rails正在尝试创建配置文件对象,这会导致意外行为(您的开发日志显示您正在发出PATCH请求,因此您尝试更新某些内容,而不是创建某些内容):

 def user_params params.require(:user).permit(:id, :username, :email, profile_attributes: [:id, :user_id, :full_name]) end 

您可能还需要更新表单以实际传递profile对象的id

请参阅此答案以获得另一种看法: https : //stackoverflow.com/a/17561608/1026898

啊,我解决了自己的问题。 对于那些人,这里是解决方案: –

从development.log,我注意到"profile" => {} 。 它应该是"profile_attributes" => {}所以我将edit.html.erb表单修改为: –

 <%= form_for :user, url: admin_user_path(@user), method: :patch do |f| %> 
<%= f.label :username %>
<%= f.text_field :username, :class => "form-control" %>
<%= f.fields_for :profile_attributes, @user.profile do |profile| %>
<%= profile.label :full_name %>
<%= profile.text_field :full_name, :class => "form-control" %>
<% end %>
<%= f.submit "Save", :class => "btn btn-primary" %>
<% end %>

然后,我在development.log中说了另一个错误: –

 ActiveRecord::RecordNotSaved (Failed to remove the existing associated profile. The record failed to save after its foreign key was set to nil.): 

所以,我再次更新我的user.rb : –

 class User < ActiveRecord::Base has_one :profile accepts_nested_attributes_for :profile, update_only: true, allow_destroy: true validates :username, :uniqueness => { :case_sensitive => false } end