我有 3 个模型:
class Post
has_many :comments
end
class Comment
belongs_to :user
belongs_to :post
end
class User
has_many :comments
end
现在在控制器中,我想调用@post.comments 并按 user.postcode 对这些评论进行排序。我尝试了以下但没有奏效:
class Post
has_many :comments, :order => "user.postcode"
end
我也试过:
class Comment
def order_by_user_postcode
includes(:user).order("user.postcode ASC")
end
end
class PostsController
@post.comments.order_by_user_postcode
end
这导致
undefined method for ActiveRecord::Relation
如何编写一个链接到@post.comments 以按user.postcode 排序的方法?