我有两个模型,一个叫做 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
我不明白这种行为。你有什么想法?