私のアプリケーションには、次のように定義された 4 つのモデルがあります。
class User < ActiveRecord::Base
has_many :comments
has_many :geographies
has_many :communities, through: :geographies
class Comment < ActiveRecord::Base
belongs_to :user
class Community < ActiveRecord::Base
has_many :geographies
has_many :users
class Geography < ActiveRecord::Base
belongs_to :user
belongs_to :community
ユーザーは、geography テーブルを介して 1 つ以上のコミュニティに関連付けられたコメントを投稿できます。
私のタスクは、ドロップダウン リストから選択したコミュニティからのコメントのみを表示することです。この投稿comment.user.communities.first
から、オブジェクト チェーンを介して特定のコメントのコミュニティにアクセスできることを知りました。
通常、ラムダを使用したnamed_scopeは、すべてのコメントのリストをフィルタリングするための推奨される選択肢のようですが、このnamed_scopeを構築する方法を完全に失っています。いくつかのRailsCastをたどってnamed_scopeを構築しようとしましたが、これは私が得ることができた限りです。生成されたエラーは以下です。
class Comment < ActiveRecord::Base
belongs_to :user
def self.community_search(community_id)
if community_id
c = user.communities.first
where('c.id = ?', community_id)
else
scoped
end
end
named_scope :from_community, { |*args| { community_search(args.first) } }
これはエラーです:
syntax error, unexpected '}', expecting tASSOC
named_scope :from_community, lambda { |*args| { community_search(args.first) } }
^
引数付きのメソッドをnamed_scopeに渡すための正しい構文は何ですか?