基于 has_one :through 关系在 Rails 3 中创建作用域

发布于 2024-10-18 03:03:33 字数 665 浏览 3 评论 0原文

Rails 3.0.3 和 Ruby 1.9.2

我有以下类

class item < ActiveRecord::Base
  belongs_to :user
  has_one :country, :through => :user

  ..

end

所以 itemA.country 产生“美国”

问题是如何为美国用户拥有的所有项目创建一个(命名)范围

当我尝试类似的操作时:

scope :american, where('countries.name' => 'United States').includes([:user, :country])

then Item即使 Item.first.country => ,.american 仍然会返回空。 “美国”

顺便说一句,在 Rails 2.3.4 版本中,我们有:

named_scope :american, :include => {:user, :country}, :conditions => { 'countries.printable_name' => 'United States' }

这正如广告中所宣传的那样。

Rails 3.0.3 and Ruby 1.9.2

I have the following class

class item < ActiveRecord::Base
  belongs_to :user
  has_one :country, :through => :user

  ..

end

So itemA.country yields "United States"

The question is how do I created a (named) scope for all items owned by US users

When I try something like:

scope :american, where('countries.name' => 'United States').includes([:user, :country])

then Item.american keeps coming back empty even when Item.first.country => 'United States'

Incidentally, in the Rails 2.3.4 version we had:

named_scope :american, :include => {:user, :country}, :conditions => { 'countries.printable_name' => 'United States' }

And that worked as advertised.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

开始看清了 2024-10-25 03:03:33

您忘记了表名的复数形式,我还认为 include 的顺序和 where 可能很重要。还建议在指定关联条件时使用联接,如下所示:

scope :american, joins(:users, :countries).where('countries.name' => 'United States')

如果您仍希望使用包含:

scope :american, includes(:users, :countries).where('countries.name' => 'United States')

You forgot to pluralize the table names, I also think the ordering of include and where may matter. It's also recommended to use a join instead when specifying conditions on associations like so:

scope :american, joins(:users, :countries).where('countries.name' => 'United States')

If you'd prefer to still use includes:

scope :american, includes(:users, :countries).where('countries.name' => 'United States')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文