2012-02-01 51 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