ruby on rails - Best way to order across associations -
i have 3 models:
class post has_many :comments end class comment belongs_to :user belongs_to :post end class user has_many :comments end
now in controller, i'd call @post.comments , order these comments user.postcode. tried following didn't work:
class post has_many :comments, :order => "user.postcode" end
i tried:
class comment def order_by_user_postcode includes(:user).order("user.postcode asc") end end class postscontroller @post.comments.order_by_user_postcode end
which results in
undefined method activerecord::relation
how can write method chain @post.comments sort user.postcode?
you must order:
has_many :comments, :order => "users.postcode"
table name users not user.
the second option:
you must implement method class method (or scope), not instance method
def self.order_by_user_postcode joins(:user).order("users.postcode asc") end
or scope:
scope :order_by_user_postcode, joins(:user).order("users.postcode asc")
Comments
Post a Comment