【问题标题】:accepts_nested_attributes_for has_many_through with validates_uniqness接受_nested_attributes_for has_many_through 和 validates_uniqness
【发布时间】: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


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多