Accepts_Nested_Attributes_For Ignore Blank Values

accepts_nested_attributes_for ignore blank values

There is a built-in validation:

:reject_if => lambda { |c| c[:name].blank? },

Destroy on blank nested attribute

You have code that says the record should be ignored if the 'where' or the 'when' is blank, on the accepts_nested _attributes line, remove the reject_if and your destroy_if blank will likely be called.

Typically to destroy, you would set a _destroy attribute on the nested record, check out the docs http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Also, just used cocoon for some of this today, and thought it was awesome, https://github.com/nathanvda/cocoon

Rails not save association if association values are empty

You may want to look at the reject_if: option for accepts_nested_attributes_for:

accepts_nested_attributes_for :sponsorship, reject_if: proc { |attributes| attributes['title'].blank? }

Looking up other questions on this matter seem to confirm this.

--

There is also reject_if: :all_blank -

accepts_nested_attributes_for :sponsorship, reject_if: :all_blank

Rails 3. Don't validate nested attributes if all left blank

I assume you have accepts_nested_attributes set up in your Student model. You need to add a :reject_if proc. It will ignore the row if the proc evaluates to true.

class Student < ActiveRecord::Base 
has_many :emergency_contacts
accepts_nested_attributes_for :emergency_contacts,
:reject_if => lambda { |a| a[:full_name].blank? }
end

You could modify it to something like lambda { |a| a[:name].blank? && a[:relationship].blank? }, etc. as your needs dictate.

Rails: use REJECT_IF only on CREATE action for nested attributes

You can create a method and instead of sending a proc into the reject_if option, which is the same, it is just more readable, so the code would look like:

accepts_nested_attributes_for :socials, reject_if: :social_rejectable?

private

def social_rejectable?(att)
att['username'].blank? && new_record?
end

You can just repeat the methods and then clean it up with some metaprogramming or add the new_record? method on the proc

accepts_nested_attributes_for :socials, reject_if: proc { |att| att['username'].blank? && new_record?}

has_one, reject_if, and accept_nested_attributes_for still triggers validation

Ok, it appears that my primary goof was trying to validate the presence of :password. I really wanted to validate the length of the password if it existed.

class WebServiceUser
devise :database_authenticatable

belongs_to :account

validates_uniqueness_of :username
validates_length_of :password, :minimum => 14, if: Proc.new { |u| !u.password.nil? }
end


Related Topics



Leave a reply



Submit