将带有参数的方法转换为验证回调

时间:2014-10-26 08:40:37

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

我有这个设置

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

我使用此方法创建一个新的SalesPrice

def create_sales_price(company_id: nil, carrier_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

    carrier_product_ids.each do |carrier_product_id|
      price_document_relation = CarrierProductSalesPrice.new({
        sales_price_id:     sales_price.id,
        carrier_product_id: carrier_product_id
      })
      price_document_relation.save!
    end
  end
  return sales_price
end

我在其中提供了一系列客户和运营商产品ID。我想进行验证,确保没有多个客户被分配过同一个运营商产品,即使是跨不同的SalesPrices。

我使用此查询来查找给定客户/运营商产品ID的匹配SalesPrice,因此实质上,我想调用此方法,并且只有在找不到匹配项时才会通过验证

def find_sales_price_from_customer_and_carrier_product(customer_id: nil, carrier_product_id: nil)
      self.joins("LEFT OUTER JOIN carrier_product_Sales_Prices ps ON sales_prices.id = ps.sales_price_id").
           joins("LEFT OUTER JOIN Customer_Price_Relations cr ON ps.sales_price_id = cr.sales_price_id").
           joins("LEFT OUTER JOIN Customers c ON cr.customer_id = c.id").
           where("cr.customer_id = ? and carrier_product_id = ?", customer_id, carrier_product_id).first
    end

问题是,我不确定如何将其转换为回调验证,因为它需要参数。

感谢任何帮助

0 个答案:

没有答案