Nathaniel Miller Nathaniel Miller - 1 year ago 67
Ruby Question

Why would one use reject_if if you can use validation?

Is there any reason you would use

and do something like this?

class User < ActiveRecord::Base
has_many :posts
accepts_nested_attributes_for :posts, reject_if: proc do |attributes|

Instead of using validation on the Post model?

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download