Rails,多态关联的混乱

时间:2010-09-24 20:24:28

标签: ruby-on-rails

我在这里有点困惑,似乎无法在网上找到合适的资源或信息。

我正在创建一个评论模型,其中可以评论任何模型,这是我做的:

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

因此评论还包含commentable_typecommentable_id

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

表单和所有内容都呈现并且工作正常,并且记录保存,commentable_typecommentable_id列除外,我不明白我在这里缺少的内容。

2 个答案:

答案 0 :(得分:1)

在控制台中执行此操作会发生什么?

c = Comment.create
t = Thing.create
c.commentable = t
c.save!

答案 1 :(得分:1)

这个问题可以帮助您解决polymorphic associations同时查看那些可以帮助您解决观点中问题的评论

这就是我回答的问题,并建议你也这样做。 由于您已在模型中创建了多态关联,因此您无需再在视图中担心这种关联。您只需在评论控制器中执行此操作。

@movie = Movie.find(id) # Find the movie with which you want to associate the comment
@comment = @movie.comments.create(:text => "This is a comment") # you can also use build
# instead of create like @comment = @movie.comments.build(:text => "This is a comment")
# and then @comment.save
# The above line will build your new comment through the movie which you will be having in
# @movie.
# Also this line will automatically save fill the commentable_id as the id of movie and 
# the commentable_type as Movie.