Dmitri
Dmitri

Reputation: 2457

Ruby on Rails get all comments

I have a (polymorphic) object Comment (which will be used for Vehicle and Review objects). How can I get all comments for User's Vehicles: @user.vehicles.comments? It says that method comments is undefined for ActiveRecord::Relation. Any simple way to get it working? Is it many-to-many relation: many vehicles have many comments? Or am I wrong? @user.vehicles.first.comments works properly.

Relationships between objects (not full):

User 
has_many Vehicles. 

Vehicle 
belongs_to User. 
has_many Comments (as commentable). 

Comment 
belongs_to Commentable, :polymorphic => true

Upvotes: 3

Views: 1570

Answers (4)

prashantsahni
prashantsahni

Reputation: 2195

Try this:

Write this in user.rb:

    has_many :comments, :through => :vehicles

Now do

 @user.comments  

It will fetch all the comments created for your vehicles

you can also fetch comments through:

    @user.vehicles(:include => :comments).collect{|v| v.comments}.flatten

But this is not the right way, in my opinion.

Upvotes: 2

vvohra87
vvohra87

Reputation: 5664

The comments part of it is just fine. The thing is - you are calling:

@user.vehicles.comments

Here, the vehicles is a AR relationship object which doesn't know anything about the comments. ie - @user.vehicles is the collection of vehicles for that user.

To get all comments on vehicles linked to the user, you can do this:

@user.vehicles.to_a.collect{|v| v.comments.to_a }.flatten

Which will return an array of all comments on any of the user's vehicles.

Upvotes: 5

Intrepidd
Intrepidd

Reputation: 20868

Try this one :

in the user model add :

has_many :comments, :through => :vehicles

Edit for vehicle and reviews :

In the user model :

has_many :comments, :through => :vehicles, :as => :comments_vehicles
has_many :comments, :through => :reviews, :as => :comments_reviews

def comments
  self.comments_vehicles + self.comments_reviews
end

Upvotes: 1

Thanh
Thanh

Reputation: 8604

I think you are try doing complex association or maybe you misunderstand about polymorphic association. It's simpler than you think. Here is associtation you should define:

User 
has_many vehicles 

Vehicle 
belongs_to user 
has_many comments, as: :commentable

Comment 
belongs_to :commentable, polymorphic: true

To get all comments of vehicle of your user, you can define a has_many :through association in User model:

User 
has_many vehicles 
has_many comments, through: :vehicles

Now you can use @user.comments to get all comments about vehicles of user.

Upvotes: 1

Related Questions