我有一个has_many:通过关联如下
Customer->
has_many :customer_materials, :dependent => :destroy
has_many :materials, :through => :customer_materials
CustomerMaterial -> #This is the lookout table for a price attribute
belongs_to :customer
belongs_to :material
Material ->
has_many :customer_materials, :dependent => :destroy
has_many :customers, :through => :customer_materials
并非所有客户都通过查找表获得此类自定义定价。只有在检查了客户的custom_price布尔值时才使用查找表。如果custom_price布尔值为false,我使用Material表中price属性跟踪的默认价格。
当我编辑客户并取消选中custom_price复选框时,我想继续并在查找表上触发级联删除。这是我的控制器更新方法。如何根据custom_price属性修改方法以进行条件更新?
def update
@customer = Customer.find(params[:id])
if @customer.update_attributes(customer_params)
flash[:success] = "Record Updated Successfully"
redirect_to customers_url
else
flash.now[:error] = @customer.errors.full_messages.to_sentence
render 'edit'
end
end
答案 0 :(得分:1)
class Customer < ActiveRecord::Base
after_save :delete_custom_prices, :unless => Proc.new {|model| model.custom_price? }
def delete_custom_prices
customer_materials.delete_all
end
end