【发布时间】:2013-12-13 20:26:08
【问题描述】:
鉴于以下模型及其关联,当它们的 step_ingredient 是已在数据库中创建/保存的成分时,我如何获取要保存的食谱。
目前,只要提供的成分不存在于成分表中,下面的代码就可以工作。需要明确的是,我不希望在我的成分表中出现重复的成分。我希望步骤成分执行类似的查找
Ingredient.find_by_title(title: 'foo')
我目前不确定回调链中的哪个位置,甚至不确定要放置哪个模型来进行行为。
食谱
class Recipe < ActiveRecord::Base
has_many :steps
accepts_nested_attributes_for :steps, :allow_destroy => true,
:reject_if => lambda { |step| step[:instructions].blank? }
validates_presence_of :name
end
成分
class Ingredient < ActiveRecord::Base
validates :title, presence: true, uniqueness: true
end
步骤
class Recipe::Step < ActiveRecord::Base
belongs_to :recipe
has_many :step_ingredients
has_many :ingredients, :through => :step_ingredients
accepts_nested_attributes_for :step_ingredients
validates_presence_of :instructions
end
步骤成分
class Recipe::StepIngredient < ActiveRecord::Base
belongs_to :step
belongs_to :ingredient
accepts_nested_attributes_for :ingredient, :reject_if => :all_blank
validates_numericality_of :amount, :only_integer => true, :allow_blank => true
delegate :name, :to => :ingredient
end
【问题讨论】:
标签: ruby-on-rails validation activerecord nested-attributes has-many-through