简体   繁体   English

使用accepts_nested_attributes_for保存两个Rails模型

[英]saving two Rails models with accepts_nested_attributes_for

I have two models: author and profile. 我有两个模型:作者和个人资料。 Author accepts_nested_attributes_for profile. 作者accepts_nested_attributes_for配置文件。 I can't figure out how to save the profile model (namely the :avatar attribute) through author. 我不知道如何通过作者保存配置文件模型(即:avatar属性)。

author.rb author.rb

class Author < ActiveRecord::Base
  has_one :profile
  accepts_nested_attributes_for :profile
end

profile.rb profile.rb

class Profile < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
  belongs_to :author
end

authors_controller.rb authors_controller.rb

class AuthorsController < ApplicationController
  before_action :set_author, only: [:show, :edit, :update, :destroy]

  def index
    @authors = Author.all.order("last_name ASC, first_name ASC")
  end

  def new 
    @author = Author.new
  end

  def create
    @author = Author.new(author_params)

    if @author.save
      AuthorMailer.activate(@author).deliver
      flash[:notice] = "Please check your email to activate your account."
      redirect_to root_path
    else
      render :new
    end

  end

  def edit
    @profile = @author.build_profile
  end

  def update 
    if @author.update(author_params)
      flash[:notice] = "Profile has been updated."
      redirect_to @author
    else
      flash[:alert] = "Profile has not been updated."
      render :edit
    end
  end

  private

    def author_params
      params.require(:author).permit(:first_name, :last_name, :email, :password, :password_confirmation, :avatar)
    end

    def set_author
      @author = Author.find(params[:id])
    end 
end

app/views/authors/edit.html.erb app / views / authors / edit.html.erb

<div class="center">
  <h1>Edit Author</h1>
</div>

<div class="row">
  <div class="col-xs-6 col-lg-4 center-block">
    <%= simple_form_for(@author, :defaults => { :wrapper_html => {:class => 'form-group'}, :input_html => { :class => 'form-control' } }) do |f| %>
      <%= f.input :first_name %>
      <%= f.input :last_name %>
      <%= f.fields_for [@author, @profile] do |p| %>
        <%= p.file_field :avatar %>
      <% end %>
      <%= f.submit "Submit", class: "btn small btn-default" %> 
    <% end %>
  </div>
</div>

This form doesn't save anything to my profile table. 此表单不会将任何内容保存到我的个人资料表。

EDIT1 updating the permit parameters didn't save anything to the profile table. EDIT1更新了allow参数,没有将任何内容保存到配置文件表中。 But I did notice that adding the following to my authors_controller in the update action saves an incomplete record to the profile table (the avatar field is blank): 但是我确实注意到,在更新操作中将以下内容添加到我的authors_controller中会将不完整的记录保存到配置文件表中(头像字段为空白):

author_controller#update author_controller#update

if @author.update(author_params)
  @profile = @author.build_profile()
  @author.profile = @profile
  flash[:notice] = "Profile has been updated."
  redirect_to @author
else
  flash[:alert] = "Profile has not been updated."
  render :edit
end

I tried placing pry inside the update action and my params look like this: 我尝试在更新操作中放置撬动,我的参数如下所示:

{"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"}

so then I tried the following in my update action: 因此,我在更新操作中尝试了以下操作:

@profile = @author.build_profile(params[:author][:profile])
@author.profile = @profile

but then I get the following error: 但随后出现以下错误:

ActiveModel::ForbiddenAttributesError in AuthorsController#update

when you use "fields_for" for a association model xxx, your params need to permit :xxx_attributes fields, which's value should be a array include it's attributes, so change your author_params method to something like this: 当您对关联模型xxx使用“ fields_for”时,您的参数需要允许:xxx_attributes字段,该字段的值应该是包含它的属性的数组,因此将author_params方法更改为如下所示:

def author_params
  params.require(:author).permit(:first_name, :last_name, :email, :password, :password_confirmation, profile_attributes: [:avatar])
end

First, you should update your params permitted fields as: 首先,您应该将参数允许的字段更新为:

def author_params
  params.require(:author).permit(:first_name, :last_name, :email, :password, :password_confirmation, :profile_attributes[:id, :avatar])
end

Second, you are mixing Rails form_for helper and Simple_form in your view. 其次,您在视图中混合了Rails form_for帮助器和Simple_form。

change 更改

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

to: 至:

<%= f.simple_fields_for [@author, @profile] do |p| %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM