Ruby on Rails has_many通过关联对象保存到数据库之前,我试图访问ActiveRecord上的关联对象。在Ruby on Rails项目中保存
class Purchase < ActiveRecord::Base
has_many :purchase_items, dependent: :destroy
has_many :items, through: :purchase_items
validate :item_validation
def item_ids=(ids)
ids.each do |item_id|
purchase_items.build(item_id: item_id)
end
end
private
def item_validation
items.each do |item|
## Lookup something with the item
if item.check_something
errors.add :base, "Error message"
end
end
end
end
如果我建立了我的对象,像这样: purchase = Purchase.new(item_ids: [1, 2, 3])
,并尝试将其保存到item_validation
方法不具备的项目集合填充呢,所以尽管项目已经设置设置它没有得到一个有机会致电check_something
方法。
是否有可能在我的购买模型和关联模型持续存在之前访问商品集合,以便我可以针对它们运行验证?
如果我改变我的item_validation
方法是:
def item_validation
purchase_items.each do |purchase_item|
item = purchase_item.item
## Lookup something with the item
if item.something
errors.add :base, "Error message"
end
end
end
它似乎工作我希望它的方式,但我觉得很难相信,有没有办法与直接访问的项目集合我购买之前的导轨以及相关记录将保存到数据库中。