Ruby on rails 3 Rails 3:使用方法调用和模型关联的命名_范围的正确语法

Ruby on rails 3 Rails 3:使用方法调用和模型关联的命名_范围的正确语法,ruby-on-rails-3,named-scope,Ruby On Rails 3,Named Scope,我的应用程序中有四个模型,定义如下 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::Bas

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

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
这就是错误:

syntax error, unexpected '}', expecting tASSOC
named_scope :from_community, lambda { |*args|  { community_search(args.first) } }
                                                            ^

将带参数的方法传递到命名的\u范围的正确语法是什么

首先,您现在可以在rails 3中使用
scope
——旧的
名为_scope
的表单被缩短了,它在rails 3.1中

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

scope :foo, { |bar|
  { :key => "was passed #{bar}" }
}
但是,在您的情况下,您正在调用
社区搜索
,它应该返回一个您可以直接返回的值。在本例中,是一个替换了这种简单散列的对象。当阅读所有关于这个主题的随机帖子和教程时,会有点困惑,这主要是因为阿雷尔在风格上造成了巨大的变化。不过,这两种样式都可以使用——可以作为lambda方法,也可以作为类方法。它们在很大程度上意味着同一件事。上面的两个链接有几个新样式的示例供进一步阅读

当然,你们可以学习一些类似的东西,我发现这更容易阅读,并且省去了很多打字

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