简体   繁体   English

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

[英]Creating a scope in Rails 3 based on a has_one :through relationship

Rails 3.0.3 and Ruby 1.9.2 Rails 3.0.3和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" 所以itemA.country产生“美国”

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' 然后,即使Item.first.country =>'United States',Item.american也会一直空着

Incidentally, in the Rails 2.3.4 version we had: 顺便说一句,在Rails 2.3.4版本中我们有:

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

And that worked as advertised. 这就像宣传的那样有效。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM