Nathaniel Miller Nathaniel Miller - 6 months ago 10
Ruby Question

Why would one use reject_if if you can use validation?

Is there any reason you would use

reject_if
and do something like this?

class User < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts, reject_if: proc do |attributes|
attributes['title'].blank?
end
end


Instead of using validation on the Post model?

class Post < ActiveRecord::Base
belongs_to :user
validates :title, presence: true
end

Answer

If you use validation, the creation of User will fail if there exists a Post which does not have a title.

If you use reject_if, the creation of User will succeed even if some, or all, of the Posts don't have titles. Only those posts without titles won't be saved.

Comments