简体   繁体   中英

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 the controller, I'd like to call @post.comments and order these comments by user.postcode. I tried the following but it didn't work:

class Post
  has_many :comments, :order => "user.postcode"
end

I also 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 for ActiveRecord::Relation

How can I write a method to chain to @post.comments to sort by user.postcode?

You must order:

has_many :comments, :order => "users.postcode"

Table name is users not user.

The second option:

You must implement the method like 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM