[英]Creating a scope in Rails 3 based on a has_one :through relationship
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])
然后,即使Item.first.country =>'United States',Item.american也會一直空着
順便說一句,在Rails 2.3.4版本中我們有:
named_scope :american, :include => {:user, :country}, :conditions => { 'countries.printable_name' => 'United States' }
這就像宣傳的那樣有效。
你忘了復數表名,我也認為包含的順序和可能重要的地方。 當指定關聯條件時,也建議使用連接,如下所示:
scope :american, joins(:users, :countries).where('countries.name' => 'United States')
如果您還想使用包括:
scope :american, includes(:users, :countries).where('countries.name' => 'United States')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.