Polymorphic Association不保存ClassName(没有STI),任何提示?

时间:2009-04-03 11:11:50

标签: ruby-on-rails activerecord associations polymorphism

我有两个模型,一个叫做Notes,另一个叫做注释。注释可以与许多其他模型相关联,因此我使用多态关联。在schema.rb中它看起来像这样:

  create_table "comments", :force => true do |t|
t.text     "body"
t.integer  "user_id"
t.integer  "commentable_id"
t.integer  "commentable_type"
t.datetime "created_at"
t.datetime "updated_at" end

当我想在注释中保存注释时,一切似乎都有效:

    # POST /comments
  # POST /comments.xml
  def create
    @comment = Comment.new(params[:comment])
    @comment.user = current_user
    respond_to do |format|
      if @comment.save
        process_file_uploads
        flash[:notice] = 'Comment was successfully created.'
        if !params[:note_id].nil?
          @note = Note.find(params[:note_id])
          debugger
          @note.comments << @comment
          format.html { redirect_to(@note) }
          format.xml  { render :xml => @note, :status => :created, :location => @note }
        else
          format.html { redirect_to(@comment) }
          format.xml  { render :xml => @comment, :status => :created, :location => @comment }
        end
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

奇怪的是,它在注释表中保存了commentable_type = 0而不是=“Note”。如果我输入@ note.comments,它仍会找到评论。

Comment Update (0.4ms)   UPDATE `comments` SET `commentable_type` = 0, `commentable_id` = 11, `updated_at` = '2009-04-03 10:55:50' WHERE `id` = 5

我不明白这种行为。你有什么想法吗?

1 个答案:

答案 0 :(得分:2)

你非常接近!只需将commentable_type列更改为字符串而不是整数,它应该正确填充(假设您的模型声明当然是正确的)。作为参考,我将包括如何设置它的示例:

# Comment model
class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

# Other models which can contain comments
class AnotherModel < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class YetAnotherModel < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

对于这种情况下的任何人,这里都会进行一次迁移:

class ChangeCommentableTypeToString < ActiveRecord::Migration
  def self.up
    change_column(:comments, :commentable_type, :string)
  end

  def self.down
    change_column(:comments, :commentable_type, :integer)
  end
end