ruby-on-rails - 通过多态关联 rails 创建对象

标签 ruby-on-rails ruby polymorphic-associations

我需要(或者我认为)在我的模型中实现多态关联,但我有问题。看我的情况,就是一个简单的问答系统,逻辑如下: - 一个问题可以用 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

Controller 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>
...

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

undefined method new' for nil:NilClass app/controllers/answers_controller.rb:52:increate'

答案? :)

最佳答案

has_one 关系中,你必须使用:

@answerable.build_answer

@answerable.create_answer

代替

@answerable.answer.new

参见 the reference了解更多信息。

关于ruby-on-rails - 通过多态关联 rails 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13351467/

相关文章:

ruby-on-rails - 找不到记录的简单 if 语句问题

php - Laravel 中可以实现这种多对多关系吗?

ruby-on-rails-3 - Rails 3-嵌套资源和多态路径: OK to two levels,但在三处中断

ruby-on-rails - Ruby - 如何加入 Rails 命令的输出?

ruby-on-rails - Rails ActiveModel 序列化程序呈现非空属性

ruby-on-rails - bundle 安装在 Rails 应用程序中创建 'parallel' 文件夹

ruby-on-rails - Rails 根据字段值更新多个记录

ruby-on-rails - Gem:将我自己的模块包含到 ActiveModel::Validations 中

ruby-on-rails - Ruby on Rails/Postgres - 如何为不存在的用户创建新数据库?

ruby-on-rails - 与注释的多态关联 - Ruby on Rails