我有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排序?
答案 0 :(得分:0)
您必须订购:
has_many :comments, :order => "users.postcode"
表名是用户而不是用户。
第二个选项:
您必须实现类方法(或范围)之类的方法,而不是实例方法
def self.order_by_user_postcode
joins(:user).order("users.postcode ASC")
end
或范围:
scope :order_by_user_postcode, joins(:user).order("users.postcode ASC")