Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 290
Kasper Avatar asked Dec 03 '12 13:12

Kasper


1 Answers

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.

like image 93
Pavel S Avatar answered Nov 16 '22 01:11

Pavel S