Created
June 1, 2011 11:38
-
-
Save MBO/1002146 to your computer and use it in GitHub Desktop.
How to convert params for nested attributes and _destroy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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