我有一个 has_many
的问题在所有 child 都有效之前不应验证的关联。
设置
rails g scaffold Hotel name
rails g scaffold RoomCategory name hotel:references
应用程序/模型/hotel.rb
class Hotel < ActiveRecord::Base
has_many :room_categories, dependent: :destroy
accepts_nested_attributes_for :room_categories,
:reject_if =>
proc {|attributes| attributes['name'].blank?},
allow_destroy: true
end
应用程序/模型/room_category.rb
class RoomCategory < ActiveRecord::Base
belongs_to :hotel
validates :name,
presence: true,
uniqueness: { scope: :hotel }
end
这个想法是给定的
hotel
不能有两个room_categories
同名。题
我如何确保以下
hotel
示例不验证为真?>> hotel = Hotel.new(name: 'Example')
>> hotel.room_categories.build(name: 'Suite')
>> hotel.room_categories.build(name: 'Suite')
>> hotel.save
>> hotel.valid?
=> true
谢谢!
最佳答案
尝试这个..
accepts_nested_attributes_for :room_categories, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
关于ruby-on-rails - 如果 has_many child 无效,则引发验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27940828/