我有 3 个模型;产品、税收和地点。每当创建产品时,如果有税,我想分配该位置的最新税。
class Location < ActiveRecord::Base
belongs_to :user
has_many :products
has_many :taxes
end
class Tax < ActiveRecord::Base
attr_accessible :date # I use this to get the latest tax
belongs_to :location
has_many :products
end
class Product < ActiveRecord::Base
attr_accessible :tax_id
belongs_to :location
belongs_to :tax
end
现在我在我的Product
模型中尝试了这个:
after_create :assign_latest_location_tax
private
def assign_latest_location_tax
if self.location.tax.present?
self.tax_id = self.location.tax.order("date DESC").first.id
end
end
但这给了我错误:
NoMethodError in ProductsController#create
undefined method `tax' for #<Location:0x4669bf0>
这样做的正确方法是什么?