Hi,
I am developing a rails 3.0.3 application and
accepts_nested_attributes_for method is giving me pains.
To simplify the issue, I created a new app and generated 2 models.
users
name: string
cars
user_id: integer
name: string
class User < ActiveRecord::Base
has_many :cars
accepts_nested_attributes_for :cars, :allow_destroy => true,
:reject_if => proc { |attrs| attrs[‘name’].blank? }
end
class Car < ActiveRecord::Base
belongs_to :user
end
Very simple, huh?
In console,
I created a user and create 2 cars for the user.
u = User.first
u.cars_attributes={“0”=>{“id”=>2, “_destroy”=>“1”}}
u.save
This should destroy the car but didn’t.
If I modify the User model like
accepts_nested_attributes_for :cars, :allow_destroy => true
Then, it works as I expect meaning it destroy the car with the same code
in the console.
If I modify the line like the following, it works also.
accepts_nested_attributes_for :cars, :allow_destroy => true, :reject_if
=> proc { |attrs| attrs[‘id’].blank? and attrs[‘name’].blank? }
As I understand it, reject_if option is only for new instance not for
destroyed instance.
Am I wrong?
Sam