使用accepts_nested_attributes更新多态关联

时间:2013-06-27 19:25:20

标签: ruby-on-rails-3 ruby-on-rails-3.2

使用rails 3.2.12,我有以下型号:

class QuestionGroup < ActiveRecord::Base
  has_many :questions

  accepts_nested_attributes_for :questions, :allow_destroy => true
  attr_accessible :title, :questions_attributes, :chapter_id
end

class Question < ActiveRecord::Base
   has_many :options

   attr_accessible :options_attributes
   accepts_nested_attributes_for :options, :allow_destroy => true
end

class MultipleChoiceQuestion < Question  
  has_many :options,
        :class_name => 'MultipleChoiceOption',
        :foreign_key => 'question_id'  
end

class MultipleChoiceOption < ActiveRecord::Base
  belongs_to :question
  attr_accessible :text
end

在控制台中,我执行以下操作将选项的文本从"OLD OPTION TEXT"更改为"NEW OPTION TEXT"

> attrs = {"questions_attributes"=>
                 {"0"=> {"type"=>"MultipleChoiceQuestion", 
                         "_destroy"=>"false", 
                         "options_attributes"=>{"0"=> {"text"=>"NEW OPTION TEXT",
                         "id"=>"67"}}, "id"=>"33"}}, "id"=>"11"}
> group = QuestionGroup.last
> group.update_attributes(attrs)
> group.questions.first.options.first.text # => "OLD OPTION TEXT"

text字段未更新。

0 个答案:

没有答案