我的应用程序中有四个模型,定义如下
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
Run Code Online (Sandbox Code Playgroud)
用户可以通过地理位表发布与一个或多个社区相关联的评论.
我的任务是仅显示从下拉列表中选择的社区的评论.我从这篇文章中了解到,我可以通过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) } }
Run Code Online (Sandbox Code Playgroud)
这是错误:
syntax error, unexpected '}', expecting tASSOC
named_scope :from_community, …Run Code Online (Sandbox Code Playgroud)