Ruby on Rails获得所有评论

Dmi*_*tri 3 ruby activerecord many-to-many ruby-on-rails polymorphic-associations

我有一个(多态)对象Comment(将用于VehicleReview对象).我怎样才能得到所有commentsUserVehicleS: @user.vehicles.comments?它说该方法comments未定义ActiveRecord::Relation.任何简单的方法让它工作?是多对多的关系:许多车辆有很多评论?还是我错了?@user.vehicles.first.comments工作正常.

对象之间的关系(不完整):

User 
has_many Vehicles. 

Vehicle 
belongs_to User. 
has_many Comments (as commentable). 

Comment 
belongs_to Commentable, :polymorphic => true
Run Code Online (Sandbox Code Playgroud)

Var*_*hra 5

评论的一部分就好了.问题是 - 你在呼唤:

@user.vehicles.comments
Run Code Online (Sandbox Code Playgroud)

这里,车辆是AR关系对象,其对评论一无所知.ie - @ user.vehicles是该用户的车辆集合.

要获得与用户链接的车辆的所有评论,您可以这样做:

@user.vehicles.to_a.collect{|v| v.comments.to_a }.flatten
Run Code Online (Sandbox Code Playgroud)

这将返回任何用户车辆上的所有评论的数组.