Rails 3:使用方法调用和模型关联更正named_scope的语法

nta*_*taj 2 named-scope ruby-on-rails-3

我的应用程序中有四个模型,定义如下

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, lambda { |*args|  { community_search(args.first) } }
                                                            ^
Run Code Online (Sandbox Code Playgroud)

将带参数的方法传递给named_scope的正确语法是什么?

小智 5

首先,您scope现在可以在rails 3中使用 - 旧版本named_scope缩短了,并且已经在rails 3.1中删除了!

但是,关于你的错误,我怀疑你不需要内部括号组.当使用像这样的lambda块时,它们通常会加倍,因为你是从头开始创建新的哈希,如下所示:

scope :foo, { |bar|
  { :key => "was passed #{bar}" }
}
Run Code Online (Sandbox Code Playgroud)

但是,在你的情况下,你正在调用community_search哪个应该返回一个你可以直接返回的值.在这种情况下,一个已替换这种简单哈希的AREL对象.在阅读有关此主题的所有随机帖子和教程时,这有点令人困惑,这主要是由于AREL造成的风格的巨大变化.但是这两种样式使用都可以 - 无论是作为lambda还是类方法.他们的意思基本相同.以上两个链接有几个这种较新风格的例子供进一步阅读.

当然,你可以学习像squeel这样的东西,我觉得它更容易阅读,并减少了大量的打字.^^;