Ruby on Rails get all comments
activerecord, many-to-many, polymorphic-associations, ruby, ruby-on-rails
Solution
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.
Problem
I have a (polymorphic) object `Comment` (which will be used for `Vehicle` and `Review` objects). How can I get all `comments` for `User`'s `Vehicle`s: `@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 ```