Has_Many 通过关联和嵌套属性

Posted

技术标签:

【中文标题】Has_Many 通过关联和嵌套属性【英文标题】:Has_Many Through Associations and Nested Attributes 【发布时间】:2015-11-07 11:37:12 【问题描述】:

我正在尝试创建一个视图,允许我直接创建和编辑我的联接表的值。这种模式被称为“雇佣”。当孩子租用最多 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,它只是提交了“books”:

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】:

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

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

【讨论】:

同样的问题...我认为这与未正确解析的属性有关。如果只是传递“书籍”,那一定是哪里出了问题?

以上是关于Has_Many 通过关联和嵌套属性的主要内容,如果未能解决你的问题,请参考以下文章

Rails has_many:通过嵌套形式

带有has_many的Rails嵌套表单:通过,如何编辑连接模型的属性?

如何在has_many中获取模型的属性:通过Rails 5中的关联

具有嵌套关联条件检查的has_many范围

带有has_many的模型中的属性总和:通过关联在Rails 5中不起作用

Rails:查找嵌套关联为空的记录