具有与同一模型的多个关联的嵌套属性

时间:2014-12-29 07:16:24

标签: ruby-on-rails nested-attributes model-associations

假设我有一个问答模型,这样一个问题有很多答案。

问题类

class Question < ActiveRecord::Base
  has_one :correct_answer, class_name: 'Answer'
  has_many :answers, class_name: 'Answer'
  accepts_nested_attributes_for :correct_answer, allow_destroy: true
  accepts_nested_attributes_for :answers, allow_destroy: true
end

答案课

class Answer < ActiveRecord::Base
  belongs_to :question
end

我希望能够创建嵌套在问题中的答案。例如:

@question = Question.new(:content => 'How many legs does a dog have?', correct_answer_attributes: {:content => '4'})

问题

当我为correct_answer(如上所述)执行此操作时,会创建一个答案和correct_answer。我怎样才能创建一个correct_answer?

2 个答案:

答案 0 :(得分:1)

你可以试试这个

 class Question < ActiveRecord::Base
   has_one :correct_answer, class_name: 'CorrectAnswer'
  ....
 end

然后

 class Answer < ActiveRecord::Base
  belongs_to :question
 end

然后

 class CorrectAnswer < Answer
 end

然后发送参数type

 @question = Question.new(:content => 'How many legs does a dog have?', answer_attributes: {:content => '4', :type => CorrectAnswer})

答案 1 :(得分:0)

我能够通过将答案的关系从has_one更改为belongs_to来解决此问题:

class Question < ActiveRecord::Base
    has_many :answers
    belongs_to :accepted_answer, :class_name => "Answer", 
                                 :foreign_key => :answer_id
end

class Answer < ActiveRecord::Base
    belongs_to :question
end