Rails 3:具有方法调用和模型关联的named_scope 的正确语法

2024-01-09

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

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 的正确语法是什么?


首先,你可以使用scope现在在 Rails 3 - 较旧的版本中named_scope表格被缩短了,它是removed http://m.onkey.org/active-record-query-interface在 Rails 3.1 中!

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

scope :foo, { |bar|
  { :key => "was passed #{bar}" }
}

但就你而言,你正在打电话community_search它应该返回一个您可以直接返回的值。在这种情况下,一个AREL http://asciicasts.com/episodes/239-activerecord-relation-walkthrough对象已经取代了这种简单的哈希值。当阅读关于这个主题的所有随机帖子和教程时,这有点令人困惑,这很大程度上是由于 AREL 造成的风格巨大变化。不过,这两种风格的 use 都可以 - 无论是作为 lambda 还是类方法。它们的意思基本上是一样的。上面的两个链接有几个这种新风格的示例,供进一步阅读。

当然,你可以只学习类似的东西squeel http://erniemiller.org/projects/squeel/,我发现它更容易阅读,并且减少了很多打字。 ^^;

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails 3:具有方法调用和模型关联的named_scope 的正确语法 的相关文章

随机推荐