尝试使用accept_nested_parameters_for我遇到了一个无法更新嵌套记录的问题。我做了很多研究,但我很确定我的问题不能通过这些其他答案来解决。相关研究:
Rails 4 deleting nested attributes, works on create but not on edit/update
Ruby on Rails - Edit/Update creating new records instead of updating
Rails 4 NOT updating nested attributes
以上所有答案都建议传递:id和我的其他嵌套参数,我已经在做的事了。有趣的是,我过去能够让它在另一个项目上工作,但是尽管几乎完全相同,但似乎无法实现这一点。
型号:
class User < ActiveRecord::Base
has_many :user_event_types
accepts_nested_attributes_for :user_event_types
...
end
class UserEventType < ActiveRecord::Base
belongs_to :user
...
end
控制器:
def update
@user = User.find(params[:id])
@user.update_attributes(user_params)
...
end
def user_params
params.require(:user).permit(:email, :password, :password_confirmation,:first_name, :last_name, :phone, user_event_types_attributes: [:id, :sms, :application, :email])
end
并且发送给控制器的params:
{
"utf8"=>"✓",
"authenticity_token"=>"...",
"user"=>{
"email"=>"email",
"first_name"=>"Some",
"last_name"=>"Body",
"phone"=>"5555555555",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]",
"user_event_types_attributes"=>{
"0"=>{
"application"=>"1",
"sms"=>"0",
"email"=>"0",
"id"=>"3"
},
"1"=>{
"application"=>"1",
"sms"=>"1",
"email"=>"0",
"id"=>"4"}
}
},
"id"=>"3"
}
通过从user_event_types_attributes中删除:id,我可以让控制器创建新记录,但它只是拒绝编辑现有记录。相反,它只是查询event_types
SELECT "user_event_types".* FROM "user_event_types" WHERE "user_event_types"."user_id" = 3 AND "user_event_types"."id" IN (3, 4)
但结果没有任何效果!
任何帮助将不胜感激!