Has_Many通过关联和嵌套属性

时间:2015-11-07 11:37:12

标签: ruby-on-rails ruby-on-rails-4 model associations nested-attributes

我正在尝试创建一个视图,允许我直接创建和编辑我的连接表的值。这种模式被称为“雇佣”。我需要能够在我的加入表中创建多行,以便孩子最多可以雇佣2本书。我遇到了一些麻烦,我怀疑这取决于我的协会...

我有3个型号。每个孩子可以有2本书:

class Child < ActiveRecord::Base
 has_many :hires
 has_many :books, through: :hires
end

class Hire < ActiveRecord::Base
 belongs_to :book
 belongs_to :child
 accepts_nested_attributes_for :book
 accepts_nested_attributes_for :child
end

class Book < ActiveRecord::Base
  has_many :hires
  has_many :children, through: :hires
  belongs_to :genres
end

控制器如下所示:

class HiresController < ApplicationController

...    

def new
    @hire = Hire.new
    2.times do
      @hire.build_book
    end
  end

 def create
    @hire = Hire.new(hire_params)

    respond_to do |format|
      if @hire.save
        format.html { redirect_to @hire, notice: 'Hire was successfully created.' }
        format.json { render :show, status: :created, location: @hire }
      else
        format.html { render :new }
        format.json { render json: @hire.errors, status: :unprocessable_entity }
      end
    end
  end

 ...    

private
    # Use callbacks to share common setup or constraints between actions.
    def set_hire
      @hire = Hire.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
        def hire_params
  params.require(:hire).permit(:child_id, book_attributes: [ :id, :book_id, :_destroy])
end
end

视图喜欢这个:

<%= form_for(@hire) do |f| %>

    <%= f.label :child_id %><br>
    <%= f.select(:child_id, Child.all.collect {|a| [a.nickname, a.id]}) -%>

    <%= f.fields_for :books do |books_form| %>


    <%= books_form.label :book_id %><br>
    <%= books_form.select(:book_id, Book.all.collect {|a| [a.Title, a.id]}) %>
        <%# books_form.text_field :book_id #%>
    <% end %>


  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

问题是,哈希没有像你期望的那样提交books_attributes,它只是提交'书籍':

Processing by HiresController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"xx", "hire"=>{"child_id"=>"1", "books"=>{"book_id"=>"1"}}, "commit"=>"Create Hire"}
Unpermitted parameter: books

我怀疑这是因为我对Hire模型的关联是:

belongs_to :book
accepts_nested_attributes_for :book

这意味着我无法正确构建属性,但我不知道如何解决这个问题。任何帮助都会很棒,我是否会严重解决这个问题?

1 个答案:

答案 0 :(得分:0)

尝试在books_param的强参数中将books_attributes更改为book_attributes。

    def hire_params
  params.require(:hire).permit(:child_id, book_attributes: [ :id, :book_id, :_destroy])
end