开发者

Rails, confusion over polymorphic associations

开发者 https://www.devze.com 2023-01-18 00:38 出处:网络
I\'m a little baffled here and can\'t seem to find the proper resource or information online. I\'m creating a comment model in which any model can be commented on, here is what I did:

I'm a little baffled here and can't seem to find the proper resource or information online.

I'm creating a comment model in which any model can be commented on, here is what I did:

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

So the comment additionally has the columns commentable_type and commentable_id,

class Thing < ActiveRecord::开发者_如何学运维Base
  has_many :comments, :as => :commentable
end

The form and everything render and work fine, and the record saves, except for the commentable_type and commentable_id columns, I don't understand what I'm missing here.


This question will help you to get around polymorphic associations also take a look at the comments those will help you to solve issues in views

This is what I answered to that and also suggest you to do the same. As you have created the polymorphic association in your model, you need not worry about that anymore in the view. You just need to do this in your Comments controller.

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


What happens when you perform this in console?

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

精彩评论

暂无评论...
验证码 换一张
取 消