2012-02-01 59 views
0

我有3 模型,用戶,商店和產品。關係是User has_many storesProduct has_many stores。在這種情況下,如果我做current_user.stores,我會得到特定用戶擁有的商店數組。但現在我想返回商店與某些產品,我可以訪問product_id,我可以做 current_user.stores.where(:product_id=>1),但事情是在我的情況下,我不能訪問product_id,所以其他方式可以我用來完成,也許has_many,範圍,但我不知道如何。有人可以幫我嗎?訪問has_many協會的ID

def my_account 
    #@product=Product.find(params[:id]) ,this cant find the id 
    if user_signed_in? 
    @my_stores=current_user.stores.where(:product_id=>@product.id) 
    end 
end 

視圖

<% @my_stores.each do |store| %> 
    <%=store.name%> 
    <%end%> 
+0

當您嘗試'什麼是你的錯誤所有的商店current_user.stores.where(:PRODUCT_ID => 1)',即是什麼阻止你訪問商店#PRODUCT_ID ? – Woahdae 2012-02-01 02:00:42

+0

'current_user.stores.where(:product_id => 1)''但是'Product.find(params [:id])''返回不能找到它沒有一個id,url沒有明顯的id。 – katie 2012-02-01 02:12:01

回答

1

的(storeproduct)具有它們之間的many-to-many關係,所以你可能要引入一箇中介模型,如下圖所示:

class User < ActiveRecord::Base 
    has_many :stores 
end 

class Store < ActiveRecord::Base 
    belongs_to :user 

    has_many :store_products 
    has_many :products, :through => :store_products 
end 

class StoreProduct < ActiveRecord::Base 
belongs_to :store 
belongs_to :product 
end 

class Product < ActiveRecord::Base 
    has_many :store_products 
    has_many :stores, :through => :store_products 
end 

現在給出用戶可以通過以下方式獲得商店:

user.stores # all stores associated with the user 

與給定的產品

user.stores.joins(:products).where("products.id = ?", 1234) 
+0

在我的情況是特別的,用戶has_many存儲和存儲belongs_to用戶雖然 – katie 2012-02-01 02:46:26

+0

答案仍然保持不變。我根據您的評論更新了模​​型。看一看。 – 2012-02-01 02:52:47

+0

Thanks.But仍然基於我的行動我無法訪問product_id,它無法找到它。 – katie 2012-02-01 02:56:28