2014-11-23 61 views
0

在我的Rails應用程序4(PostgreSQL的DB)委託的屬性4查詢我有以下的模型結構:的Rails從聯想的has_many

class Product 
    has_many :items 
end 

class Item 
    belongs_to :user 
    belongs_to :product 
end 

class User 
    has_one :profile 
    delegate :name, to: :profile 
end 

class Profile 
    belongs_to :user 
end 

我無法通過在Product做一個查詢Items該項目的用戶名稱。有幾件事情我已經試過:

Product.first 
    .items 
    .includes(:user) 
    .where("user.name = ?", "Blah") 
    .references(:user) 

Item.where(product_id: 2) 
    .includes(:user) 
    .where("user.name = ?", "Blah") 
    .references(:user) 

我也試着搞什麼下面沒有成功:

Product.first 
    .items 
    .includes(user: :profile) 
    .where("items.user.profile.name = ?", "Blah") 
    .references(:user) 

所有上述查詢給我的語法錯誤。我確定我在做一些愚蠢的事情,但是想知道是否有人能幫我弄清楚如何執行我的查詢。

回答

0
Product.first.items.joins(user: :profile).where(profiles: {name: "Blah"}) 
+0

唉,我試過類似的東西,並且使用'profile'而不是'profiles'。謝謝! – tvalent2 2014-11-23 16:45:28