10

我需要(或我认为)在我的模型中实现多态关联,但我有问题。让我们看看我的情况,这是一个简单的问答系统,逻辑如下: - 一个问题可以由 N 个答案来回答。- 答案只能是“文本”异或(一个或另一个,而不是两者)“图片”。

迁移:

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创建'

答案?:)

4

1 回答 1

23

在一段has_one关系中,你必须使用:

@answerable.build_answer

或者

@answerable.create_answer

代替

@answerable.answer.new

有关更多信息,请参阅参考资料

于 2012-11-13T11:51:33.690 回答