2012-07-03 48 views
1

我有四个型号在我的应用程序,定义为named_scope正确的语法如下的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 

用户可以发表评论,这是与一个或多个社区通过地理相关表。

我的任务是仅显示从下拉列表中选择的社区评论。我从this post得知我可以通过comment.user.communities.first对象链访问给定评论的社区。

这似乎通常与拉姆达一个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正确的语法?

回答

4

首先,您现在可以在rails 3中使用scope - 较早的named_scope表单被缩短了,它在rails 3.1中的removed

关于你的错误,虽然,我怀疑你不需要内部的一组括号。

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

在你的情况,不过,你在呼唤community_search应返回一个值,你可以:使用像这样的拉姆达块时,因为你是从头开始创建新的哈希值,这样它们通常一倍,直接返回。在这种情况下,一个AREL对象已经取代了这种简单的哈希。在阅读所有关于这个主题的随机帖子和教程时,这有点令人困惑,这很大程度上是由于AREL引起的风格的巨大变化。尽管这两种风格的用法都可以,不管是作为lambda还是类方法。他们主要是指同样的事情。以上两个链接有几个这种新的风格的例子进一步阅读。

当然,你可能只是学到一些东西像​​,我觉得这更容易阅读,并减少了大量的打字。 ^^;