1

私は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 でソートするメソッドを作成するにはどうすればよいですか?

4

1 に答える 1

0

注文する必要があります:

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

テーブル名はユーザーではなくユーザーです。

2 番目のオプション:

インスタンスメソッドではなく、クラスメソッド(またはスコープ)のようなメソッドを実装する必要があります

 def self.order_by_user_postcode
   joins(:user).order("users.postcode ASC")
 end

またはスコープ:

scope :order_by_user_postcode, joins(:user).order("users.postcode ASC")
于 2013-04-20T13:02:20.727 に答える