Поля_для has_many ассоциаций не сохраняются

Итак, у меня есть глубоко укоренившаяся ассоциация между опросами, вопросами и ответами:

class Poll < ActiveRecord::Base
  attr_accessible :description, :end_time, :start_time, :title, :user_id, :questions_attributes, :is_live

  belongs_to :user
  has_many :questions, :dependent => :destroy
  # This is the plularized form of sms, it's not smss
  has_many :sms, :through => :questions 
  has_many :feedbacks

  accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank?}, :allow_destroy => true
end

class Question < ActiveRecord::Base
  attr_accessible :poll_id, :title, :answer_attributes

  belongs_to :poll
  has_many :answers, :dependent => :destroy
  # THis is the plularized form of sms, it's not smss
  has_many :sms
                                          #If someone creates a form with a blank question field at the end, this will prevent it from being rendered on teh show page
  accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank?}, :allow_destroy => true

end

class Answer < ActiveRecord::Base
  attr_accessible :is_correct, :question_id, :title

  belongs_to :question
end

И я пытаюсь сохранить все объекты в одной форме fields_for вот так.

= form_for @poll, :class=>'create-poll-form' do |f|
  = f.text_field :title, :autofocus => true, :placeholder => "Poll Title"
  = f.text_field :description, :placeholder => 'Description'  
  = f.fields_for :questions do |builder| 
    = render "questions/question_fields", :f => builder

  = f.submit "Create Poll", :class => 'btn btn-danger'

Частичные вопросы

%p
  = f.label :title, "Question"
  = f.text_field :title
  = f.check_box :_destroy
  = f.label :_destroy, "Remove Question"
%p
  = f.fields_for :answers do |builder|
    = render "answers/answer_fields", :f => builder

Ответы неполные

%p
  = f.label :title, "Answer"
  = f.text_field :title
  = f.check_box :_destroy
  = f.label :_destroy, "Remove Answer"

Однако PollsController не сохраняет данные:

  def create
    binding.pry
    @poll = current_user.polls.new(params[:poll])
    # @poll = Poll.create(params[:poll])
    binding.pry
    @poll.save!
    redirect_to root_path
  end

  def new
    @poll = Poll.new  

    1.times do
      question = @poll.questions.build
      2.times {question.answers.build}
    end
  end

Любые советы здесь были бы потрясающими, я немного работал над этим, и это ставит меня в тупик! Заранее спасибо!

Также вот лог сервера:

Started POST "/polls" for 127.0.0.1 at 2013-06-06 20:14:47 -0400
Processing by PollsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"hk+KuNsTLx3sH9pE7Mf8XETGsmxTsRN4/tWUBn3CIVE=", "poll"=>{"title"=>"Testing 1-2-1-2", "description"=>"Up on the mic", "questions_attributes"=>{"0"=>{"title"=>"Cake or Death?", "_destroy"=>"0", "answers_attributes"=>{"0"=>{"title"=>"Cake", "_destroy"=>"0"}, "1"=>{"title"=>"Death", "_destroy"=>"0"}}}}}, "commit"=>"Create Poll"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
  Question Load (0.5ms)  SELECT "questions".* FROM "questions" WHERE "questions"."poll_id" IS NULL
   (0.3ms)  BEGIN
  SQL (47.6ms)  INSERT INTO "polls" ("created_at", "description", "end_time", "is_live", "start_time", "title", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"  [["created_at", Fri, 07 Jun 2013 00:16:46 UTC +00:00], ["description", "Up on the mic"], ["end_time", nil], ["is_live", nil], ["start_time", nil], ["title", "Testing 1-2-1-2"], ["updated_at", Fri, 07 Jun 2013 00:16:46 UTC +00:00], ["user_id", 1]]
   (0.8ms)  COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 170668ms (ActiveRecord: 54.9ms)

person Keith Johnson    schedule 07.06.2013    source источник


Ответы (1)


Я не уверен, что это проблема, но в вашем

class Question < ActiveRecord::Base
  attr_accessible :poll_id, :title, :answer_attributes

но в вашем лог-файле есть

Parameters: {"utf8"=>"✓", "authenticity_token"=>"hk+KuNsTLx3sH9pE7Mf8XETGsmxTsRN4/tWUBn3CIVE=", "poll"=>{"title"=>"Testing 1-2-1-2", "description"=>"Up on the mic", "questions_attributes"=>{"0"=>{"title"=>"Cake or Death?", "_destroy"=>"0", "answers_attributes"=>{"0"=>{"title"=>"Cake", "_destroy"=>"0"}, "1"=>{"title"=>"Death", "_destroy"=>"0"}}}}}, "commit"=>"Create Poll"}

Разница составляет :answers_attributes, а не :answer_attributes, т. е. ответ vs ответ*s

Это может привести к тому, что данные будут выброшены.

person muttonlamb    schedule 07.06.2013
comment
Из любопытства, он все еще терпит неудачу, если вы удаляете оба reject_ifs? - person muttonlamb; 07.06.2013
comment
Нет, теперь работает! Ну хоть без лямбды, спасибо! - person Keith Johnson; 08.06.2013
comment
Хорошо, по крайней мере, теперь вы знаете, на чем сосредоточиться. Должно быть, по какой-то причине выбрасывал атрибуты. PS, если это было полезно, проголосуйте за :) подсказка подсказка.... - person muttonlamb; 08.06.2013