Has_Many чрез асоциации и вложени атрибути

Опитвам се да създам изглед, който ми позволява да създавам и редактирам директно стойности на моята таблица за присъединяване. Този модел се нарича „наем“. Трябва да мога да създам множество редове в моята таблица за свързване, когато дете наеме до 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

което означава, че не мога да създам правилно атрибутите, но не съм сигурен как да реша това. Всяка помощ би била чудесна, лошо ли решавам този проблем?


person James Osborn    schedule 07.11.2015    source източник


Отговори (1)


Опитайте да промените books_attributes на book_attributes в силни параметри за hire_param.

    def hire_params
  params.require(:hire).permit(:child_id, book_attributes: [ :id, :book_id, :_destroy])
end
person Padhu    schedule 07.11.2015
comment
Същият проблем... Мисля, че е свързано с това, че атрибутите не са анализирани правилно. Ако се предават само „книги“, трябва нещо да се обърка там? - person James Osborn; 07.11.2015