accepted_nested_attributes_for has_many通过validatesuniquenessof

时间:2013-12-13 20:26:09

标签: ruby-on-rails validation activerecord nested-attributes has-many-through

鉴于以下模型及其关联,当step_ingredient是已在数据库中创建/保存的成分时,如何获取要保存的配方。

目前,只要提供的成分在Ingredients表中不存在,下面的代码就可以使用。为了清楚起见,我不想在我的成分表中复制成分。我希望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

成分<​​/ P>

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

1 个答案:

答案 0 :(得分:0)

似乎偶然发现了我自己问题的解决方案。

class Recipe::RowIngredient < ActiveRecord::Base

  belongs_to :row
  belongs_to :ingredient

  accepts_nested_attributes_for :ingredient, reject_if: :all_blank

  before_validation :get_ingredient

  def get_ingredient
    self.ingredient = Ingredient.find_or_create_by(title: ingredient.title)
  end

end