Kasper
Kasper

Reputation: 227

rails accepts_nested_attributes and :reject_if

I have a form with nested attributes. Now in my :reject_if => statement i would like to check an attribute on the nested model, say first_record? Is there a way to access such a method? It seems to me that you can only access the submitted attribute hash, to check if a field is blank for example. Thanks!

Upvotes: 8

Views: 4535

Answers (1)

Pavel S
Pavel S

Reputation: 1543

According to docs http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Alternatively, :reject_if also accepts a symbol for using methods:

class Member < ActiveRecord::Base
  has_many :posts
  accepts_nested_attributes_for :posts, :reject_if => :new_record?
end

class Member < ActiveRecord::Base
  has_many :posts
  accepts_nested_attributes_for :posts, :reject_if => :reject_posts

  def reject_posts(attributed)
    attributed['title'].blank?
  end
end

This should work for you. Basically that means that in custom function you can do anything you want.

Upvotes: 7

Related Questions