2010-09-24 83 views
1

我在这里有点困惑,似乎无法在网上找到适当的资源或信息。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列,我不明白我在这里失踪。

+0

你能在这里展示你的表单吗?因为模型中的所有内容似乎都是正确的 – Bohdan 2010-09-24 21:29:35

回答

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

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

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