What is validation ?
Validations are required for ensuring that the received data is correct and valid. If the received data is valid then we do the further processing with the data.Nested Model Validation
Nested model is sometimes tricky when you have complex associations. Here I'm explaining how we can do nested model validation.
We use nested form to save associations through its parent model.
Generally we do:
class Album < ActiveRecord::Base
has_many :songs
accepts_nested_attributes_for :songs
end
Now suppose we want all the songs to be removed on removal of the album.
class Album < ActiveRecord::Base
has_many :songs
accepts_nested_attributes_for :songs, :allow_destroy => true
end
class Album < ActiveRecord::Base
has_many :songs
accepts_nested_attributes_for :songs,
:allow_destroy => true,
:reject_if => proc {|attrs| attrs['name'].blank? }
end
class Album < ActiveRecord::Base
has_many :songs
accepts_nested_attributes_for :songs,
:allow_destroy => true,
:reject_if => proc {|attrs| attrs['name'].blank? }
validate :must_have_one_song
def must_have_one_song
errors.add(:songs, 'must have one song') if songs_empty?
end
def songs_empty?
songs.empty?
end
end
class Album < ActiveRecord::Base
has_many :songs
accepts_nested_attributes_for :songs,
:allow_destroy => true,
:reject_if => proc {|attrs| attrs['name'].blank? }
validate :must_have_one_song
def must_have_one_song
errors.add(:songs, 'must have one song') if songs_empty?
end
def songs_empty?
songs.empty? or songs.all? {|song| song.marked_for_destruction? }
end
end
Comments
Post a Comment