Ruby on rails 保存带有嵌套属性的两个Rails模型

Ruby on rails 保存带有嵌套属性的两个Rails模型,ruby-on-rails,Ruby On Rails,我有两个模型:作者和简介。作者接受配置文件的\u嵌套属性\u。我不知道如何通过author保存配置文件模型,即:avatar属性 author.rb 我尝试在更新操作中放置pry,我的参数如下所示: {"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"EROrMzOejPmMU/wzlnC5iaoTPu4pyBXelHAs3uiPA2U=", "author"=> {"first_name"=>

我有两个模型:作者和简介。作者接受配置文件的\u嵌套属性\u。我不知道如何通过author保存配置文件模型,即:avatar属性

author.rb

我尝试在更新操作中放置pry,我的参数如下所示:

{"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>"EROrMzOejPmMU/wzlnC5iaoTPu4pyBXelHAs3uiPA2U=",
 "author"=>
  {"first_name"=>"Mike",
   "last_name"=>"Glaz",
   "profile"=>
    {"avatar"=>
      #<ActionDispatch::Http::UploadedFile:0x007feb48127ab0
       @content_type="image/jpeg",
       @headers=
    "Content-Disposition: form-data; name=\"author[profile][avatar]\"; filename=\"me_and_lekeziah.jpg\"\r\nContent-Type: image/jpeg\r\n",
       @original_filename="me_and_lekeziah.jpg",
       @tempfile=#<File:/tmp/RackMultipart20140504-15793-l4uu6l>>}},
 "commit"=>"Submit",
 "action"=>"update",
 "controller"=>"authors",
 "id"=>"3"}
def author_params
  params.require(:author).permit(:first_name, :last_name, :email, :password, :password_confirmation, profile_attributes: [:avatar])
end
但是我得到了以下错误:

ActiveModel::ForbiddenAttributesError in AuthorsController#update

当您为关联模型xxx使用字段_时,您的参数需要允许:xxx_attributes字段,其值应为包含其属性的数组,因此将author_params方法更改为类似以下内容:

{"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>"EROrMzOejPmMU/wzlnC5iaoTPu4pyBXelHAs3uiPA2U=",
 "author"=>
  {"first_name"=>"Mike",
   "last_name"=>"Glaz",
   "profile"=>
    {"avatar"=>
      #<ActionDispatch::Http::UploadedFile:0x007feb48127ab0
       @content_type="image/jpeg",
       @headers=
    "Content-Disposition: form-data; name=\"author[profile][avatar]\"; filename=\"me_and_lekeziah.jpg\"\r\nContent-Type: image/jpeg\r\n",
       @original_filename="me_and_lekeziah.jpg",
       @tempfile=#<File:/tmp/RackMultipart20140504-15793-l4uu6l>>}},
 "commit"=>"Submit",
 "action"=>"update",
 "controller"=>"authors",
 "id"=>"3"}
def author_params
  params.require(:author).permit(:first_name, :last_name, :email, :password, :password_confirmation, profile_attributes: [:avatar])
end

首先,应将参数允许字段更新为:

def author_params
  params.require(:author).permit(:first_name, :last_name, :email, :password, :password_confirmation, :profile_attributes[:id, :avatar])
end
第二,在视图中混合使用Rails表单和简单表单作为助手

改变

<%= f.fields_for [@author, @profile] do |p| %>
致:

ActiveModel::ForbiddenAttributesError in AuthorsController#update
def author_params
  params.require(:author).permit(:first_name, :last_name, :email, :password, :password_confirmation, profile_attributes: [:avatar])
end
def author_params
  params.require(:author).permit(:first_name, :last_name, :email, :password, :password_confirmation, :profile_attributes[:id, :avatar])
end
<%= f.fields_for [@author, @profile] do |p| %>
<%= f.simple_fields_for [@author, @profile] do |p| %>