通过Polymorphic association rails创建对象

Mar*_* B. 9 ruby ruby-on-rails polymorphic-associations

我需要(或者我认为)在我的模型中实现多态关联,但是我有些不对劲.让我们看看我的情况,这是一个简单的问题/答案系统,逻辑如下: - 一个问题可以通过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
Run Code Online (Sandbox Code Playgroud)

型号 *answer.rb*

class Answer < ActiveRecord::Base
    belongs_to :user_id
    belongs_to :question_id
    belongs_to :answerable, :polymorphic => true

    attr_accessible :answerable_type
end
Run Code Online (Sandbox Code Playgroud)

answer_text.rb

class AnswerText < ActiveRecord::Base
    TYPE = "text"

    has_one :answer, :as => :answerable

    attr_accessible :content
end
Run Code Online (Sandbox Code Playgroud)

answer_picture.rb

class AnswerPicture < ActiveRecord::Base
    TYPE = "picture"

    has_one :answer, :as => :answerable

    attr_accessible :content
end
Run Code Online (Sandbox Code Playgroud)

控制器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
...
Run Code Online (Sandbox Code Playgroud)

并查看表单(只有这些字段):

...
<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>
...
Run Code Online (Sandbox Code Playgroud)

所以,问题是当我提交表单时,我收到此错误:

未定义的方法new' for nil:NilClass app/controllers/answers_controller.rb:52:in创建'

答案?:)

m_x*_*m_x 21

has_one关系上,你必须使用:

@answerable.build_answer
Run Code Online (Sandbox Code Playgroud)

要么

@answerable.create_answer
Run Code Online (Sandbox Code Playgroud)

代替

@answerable.answer.new
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅参考.