gpt4 book ai didi

ruby-on-rails-3 - 导轨 3 : Correct syntax for named_scope with method call and model associations

转载 作者:行者123 更新时间:2023-12-02 05:38:46 25 4
gpt4 key购买 nike

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

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 对象链访问给定评论的社区。

通常情况下,带有 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 的正确语法是什么?

最佳答案

首先,您现在可以在 Rails 3 中使用 scope - 较旧的 named_scope 形式已缩短,它是 removed在 Rails 3.1 中!

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

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

不过,在您的情况下,您正在调用 community_search,它应该返回一个您可以直接返回的值。在这种情况下,一个 AREL替换了这种简单哈希的对象。阅读所有关于这个主题的随机帖子和教程时,它有点令人困惑,这主要是由于 AREL 导致的风格的巨大变化。不过,这两种样式都可以使用 - 作为 lambda 或类方法。它们在很大程度上意味着同一件事。上面的两个链接有几个这种新样式的示例,供进一步阅读。

当然,你可以只学习类似 squeel 的东西,我发现它更容易阅读,并且减少了很多输入。 ^^;

关于ruby-on-rails-3 - 导轨 3 : Correct syntax for named_scope with method call and model associations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11303772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com