1

我有两个模型,一个叫做 Notes,一个叫做 Comments。评论可以与许多其他模型相关联,因此我使用多态关联。在 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

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

4

1 回答 1

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
于 2009-04-03T12:23:30.587 回答