我的应用程序中有四个模型,定义如下
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
用户可以发表评论,这些评论通过地理表与一个或多个社区相关联。
我的任务是仅显示从下拉列表中选择的社区的评论。我从中学到了这个帖子 https://stackoverflow.com/questions/11278577/rails-3-object-chaining-with-has-many-through-associations我可以通过以下方式访问给定评论的社区comment.user.communities.first
对象链。
看起来通常带有 lambda 的named_scope 是过滤所有注释列表的首选,但是,我完全不知道如何构造这个named_scope。我尝试通过遵循一些 RailsCasts 来构造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 的正确语法是什么?