【问题标题】:ActiveRecord Validation: association saved even if validation failedActiveRecord 验证:即使验证失败也保存关联
【发布时间】:2011-08-11 13:18:21
【问题描述】:

错误被添加到记录的错误对象中,但关联仍然被保存。

  class Parent < ActiveRecord::Base
      validate :valid_child?

      #validation methods
      protected
      def valid_child?
         @child_names = Hash.new
         self.children.each do |curr_child|
            if @child_names[curr_child.name].nil?
                @child_names[curr_child.name] = curr_child.name
            else
                errors.add(:base, "child name should be unique for children associated to the parent")
            end
         end
      end
      #associations
      has_and_belongs_to_many :children, :join_table => 'map__parents__children'
 end


#query on rails console

 @parent = Parent.find(1)
 @parent.children_ids = [1, 2]
 @parent.save

【问题讨论】:

    标签: ruby-on-rails-3 validation activerecord associations


    【解决方案1】:

    问题在于,对于现有记录,@parent.children_ids = [1, 2] 将在调用 @parent.save 之前使数据库中的更改生效。

    尝试使用validates_associated 验证孩子而不是滚动您自己的验证。

    为确保子名称在父上下文中是唯一的,请使用 validates_uniqueness_of:scope 选项来确定父 ID 的唯一性。比如:

    class Child < ActiveRecord::Base
      belongs_to :parent
      validates_uniqueness_of :name, :scope => :parent
    end
    

    【讨论】:

    • 子名对于父级的所有子级应该是唯一的。一般来说,孩子的名字可以相同。因此验证与父母和孩子都相关联。 validates_related 在这里不起作用。请提出其他替代方案
    • 请查看我的答案的编辑版本,其中包含有关 validates_uniqueness_of 的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 2010-10-30
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多