Klaus Turbo
Klaus Turbo

Reputation: 2960

Skip validations for nested attributes in Rails 3?

I'm currently working with nested forms/fields_for and I was wondering if there was an easy way to skip validations for nested attributes?

Can I maybe squeeze a object.nested_object.save(:validate => false) in somewhere?

Upvotes: 1

Views: 2837

Answers (1)

shingara
shingara

Reputation: 46914

You just need do your save in two part. The first save about the parent saving and second part about nested

If you use an accepts_nested_attributes_for on this nested field

def create
  nested_params = params[:object].delete(:nested_attributes)
  if object = Object.create(params[:object]) && 
    object.update_attributes(nested_params, :validate => false)
    redirect_to object_url(object)
  else
    render :new
  end
end

Update with comment from Cojones :

If you don't use this option you need assign directly the nested_attribute like explain on comment :

def create
  nested_params = params[:object].delete(:nested_attributes)
  if object = Object.create(params[:object]) && 
    object.nested_object.update_attributes(nested_params, :validate => false)
    redirect_to object_url(object)
  else
    render :new
  end
end

Please see comment for more information.

Upvotes: 4

Related Questions