我有3个型号。这些是User
,Product
和Price
模型。我希望Users
能够订阅Products
并以更低的价格观看Price
模型。我正在考虑如何设置它,但没有找到正确的关联。
截至目前我的协会是这样的:
注意:为简单起见,许多字段(表格列也已删除)
class User
has_many :prices, :dependent => :destroy
has_many :products, :through => :prices
end
class Product
# table columns - :name
has_many :prices
has_many :users, :through => :prices
end
class Price
# table columns - :cost, :user_id, :product_id, :store_id
belongs_to :user
belongs_to :product
belongs_to :store
end
我打算通过在名为Product
的{{1}}模型中创建一个布尔值来设置它,但我会陷入关联。我应该:watch_product
Product
还是反过来?我有user_id
个关联但:through
上没有user_id
或Product
上有product_id
。 User
应该改为watch_product
吗?
答案 0 :(得分:1)
我不会将用户信息存储在Price
模型中。我将介绍一个单独的模型,用于存储用户到产品订阅。
class User
has_many :user_products
has_many :products, :through => :user_products
has_many :prices, :through => :products
end
class UserProduct
belongs_to :user
belongs_to :product
end
class Product
has_many :prices
has_many :user_products
has_many :users, :through => :user_products
end
class Price
# table columns - :cost, :product_id, :store_id
belongs_to :product
belongs_to :store
scope :by_product, lambda {|product| where(:product_id => product)}
scope :by_store, lambda {|store| where(:store_id => store)}
end
现在您可以按如下方式获取用户的价格:
user.prices.by_product(12)
user.prices.by_store(10)
user.prices.by_product(12).by_store(10)