为基于订阅的模型创建关联?

时间:2012-04-03 16:27:07

标签: ruby-on-rails ruby ruby-on-rails-3.1

我有3个型号。这些是UserProductPrice模型。我希望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_idProduct上有product_idUser应该改为watch_product吗?

1 个答案:

答案 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)
相关问题