Skip to content

Instantly share code, notes, and snippets.

@MBO
Created June 1, 2011 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MBO/1002146 to your computer and use it in GitHub Desktop.
Save MBO/1002146 to your computer and use it in GitHub Desktop.
How to convert params for nested attributes and _destroy
Convert params in form:
"product_suppliers_attributes"=>{
"0"=>{"id"=>"2", "_destroy"=>"false", "supplier_id"=>"1"},
"1"=>{"id"=>"3", "_destroy"=>"false", "supplier_id"=>"3"}
}
to form:
"product_suppliers_attributes"=>[
{"id"=>"2", "_destroy"=>"false", "supplier_id"=>"1"},
{"id"=>"3", "_destroy"=>"false", "supplier_id"=>"3"}
]
So you can for example use in your views:
hidden_field_tag "product[product_suppliers_attributes][_destroy]", "true"
check_box_tag "product[product_suppliers_attributes][_destroy]", "false"
to allow user to decide if you want to leave nested relation or delete in single table view.
class ApplicationController < ActionController::Base
def self.convert_nested_params(*args)
model_name = controller_name.sub(/Controller$/, '').singularize.underscore.to_sym
options = args.extract_options!
args.each do |nested_params_name|
before_filter options do |controller|
nested_params = controller.params[model_name][nested_params_name]
if nested_params.present?
logger.info "Converting params for #{model_name}, nested_params: #{nested_params.inspect}"
params[model_name][nested_params_name] = nested_params.inject([]) do |acc,el|
acc << el.last
end
logger.info "Params after conversion: #{params.inspect}"
end
end
end
end
end
class ProductsController < ApplicationController
convert_nested_params :product_suppliers_attributes, :only => [:create, :update]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment