1

我試圖創建一個視圖,允許我直接創建和編輯我的連接表的值。這種模式被稱爲'僱用'。我需要能夠在我的加入表格中創建多行,以便孩子可以租用2本書。我有一些麻煩,我懷疑這是我的協會...Has_Many通過關聯和嵌套屬性

我有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 

我懷疑這是因爲我對租用模型關聯是:

​​

,這意味着我不能建立正確的屬性,但我不知道如何解決這個問題。任何幫助都會很好,我是否很難解決這個問題?

回答

0

嘗試在hire_param的strong參數中將books_attributes更改爲book_attributes。

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

同樣的問題......我認爲這是關於不正確解析的屬性。如果只有'書籍'被通過,那麼在那裏肯定有問題? –