我需要(或者我认为)在我的模型中实现多态关联,但是我有些不对劲。让我们看看我的情况,这是一个简单的问题/答案系统,逻辑如下: - N个答案可以回答一个问题。 - 答案可能只是“文本”XOR(一个或另一个,而不是两个)“图片”。
迁移
class CreateAnswers < ActiveRecord::Migration
def change
create_table :answers do |t|
t.integer :question_id
t.references :answerable, :polymorphic => true
t.timestamps
end
end
end
class CreateAnswerTexts < ActiveRecord::Migration
def change
create_table :answer_texts do |t|
t.text :content
t.timestamps
end
end
end
class CreateAnswerPictures < ActiveRecord::Migration
def change
create_table :answer_pictures do |t|
t.string :content
t.timestamps
end
end
end
模型 * answer.rb *
class Answer < ActiveRecord::Base
belongs_to :user_id
belongs_to :question_id
belongs_to :answerable, :polymorphic => true
attr_accessible :answerable_type
end
answer_text.rb
class AnswerText < ActiveRecord::Base
TYPE = "text"
has_one :answer, :as => :answerable
attr_accessible :content
end
answer_picture.rb
class AnswerPicture < ActiveRecord::Base
TYPE = "picture"
has_one :answer, :as => :answerable
attr_accessible :content
end
控制器 answers_controller.rb:
...
def create
post = params[:answer]
create_answerable(post[:answerable_type], post[:answerable])
@answer = @answerable.answer.new()
end
private
def create_answerable(type, content)
@answerable = ('Answer' + type.capitalize).classify.constantize.new(:content => content)
@answerable.save
end
...
并查看表单(仅限这些字段):
...
<div class="field">
<%= f.label :answerable_type %><br />
<%= select("answer", "answerable_type", Answer::Types, {:include_blank => true}) %>
</div>
<div class="field">
<%= f.label :answerable %><br />
<%= f.text_field :answerable %>
</div>
...
所以,问题是当我提交表单时,我收到此错误:
未定义的方法
new' for nil:NilClass app/controllers/answers_controller.rb:52:in
创建'
答案? :)
答案 0 :(得分:21)
在has_one
关系中,你必须使用:
@answerable.build_answer
或
@answerable.create_answer
而不是
@answerable.answer.new
请参阅the reference了解详情。