问题描述:

I have 3 models,user,store and product. The relationship is User has_many stores, and Product has_many stores. In this case if i do current_user.stores, I get an array of stores the particular user has. But now I want to return stores with certain products where I could have access to product_id, which I could do

current_user.stores.where(:product_id=>1), but the thing is in my case, I can't access the product_id , so which other way could I use to accomplish that, maybe has_many, scope but I don't know how. Can anybody help me please?

 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

view

 <% @my_stores.each do |store| %>

<%=store.name%>

<%end%>

网友答案:

The (store, product) has a many-to-many relationship between them, so you might have to introduce an intermediary model as shown below:

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

Now given a user you can get the stores as follows:

user.stores # all stores associated with the user

All stores with the given product

user.stores.joins(:products).where("products.id = ?", 1234)
相关阅读:
Top