多表唯一性约束

时间:2014-10-14 17:11:34

标签: ruby-on-rails ruby-on-rails-4

我有以下设置。 SalesPrice可以拥有许多客户和许多产品。产品可以有很多销售价格,客户也可以。我想在SalesPrice上强制执行约束,这样每个客户只能被分配到另一个产品一次,甚至可以分配给SalesPrices。

SalesPrice1 = C1, C2, P1
SalesPrice2 = C1, C3, P1, P3

以上,在两个SalesPrices中,客户1(C1)与同一产品(P1)链接两次,这是不可能的。我有点困惑,因为我使用了很多连接表,所以我将如何实现这一目标?

class Customer < ActiveRecord::Base
  has_many :customer_price_relations
  has_many :sales_prices, through: :customer_price_relations (join table)

class SalesPrice < ActiveRecord::Base
  has_many :product_sales_prices, dependent: :destroy (join table)
  has_many :products, through: :product_sales_prices
  has_many :customer_price_relations, dependent: :destroy (join table)
  has_many :customers, through: :customer_price_relations  

class Product < ActiveRecord::Base
  has_many   :product_sales_prices
  has_many   :sales_prices, through: :product_sales_prices (join table)

作业方法:

def create_sales_price(company_id: nil, product_ids: nil, customer_ids: nil,
                       name: nil, margin_percentage: nil)
  sales_price = nil

  transaction do 
    sales_price = self.new({
      company_id:        company_id,
      name:              name,
      margin_percentage: margin_percentage
    })
    sales_price.save!

    customer_ids.each do |customer_id|
      customer_price_relation = CustomerPriceRelation.new({
        customer_id: customer_id,
        sales_price_id: sales_price.id
      })
      customer_price_relation.save!
    end

    product_ids.each do |product_id|
      price_document_relation = ProductSalesPrice.new({
        sales_price_id: sales_price.id,
        product_id: product_id
      })
      price_document_relation.save!
    end
  end

  return sales_price
end

非常感谢任何帮助

0 个答案:

没有答案