Rails: change form parameters before modifying the database

I am working on a Rails application that submits data through a form. I want to change some "parameters" of the form after submitting the form, but before processing it.

What I have right now

{"commit"=>"Create", "authenticity_token"=>"0000000000000000000000000" "page"=>{ "body"=>"TEST", "link_attributes"=>[ {"action"=>"Foo"}, {"action"=>"Bar"}, {"action"=>"Test"}, {"action"=>"Blah"} ] } } 

What I want

 {"commit"=>"Create", "authenticity_token"=>"0000000000000000000000000" "page"=>{ "body"=>"TEST", "link_attributes"=>[ {"action"=>"Foo", "source_id"=>1}, {"action"=>"Bar", "source_id"=>1}, {"action"=>"Test", "source_id"=>1}, {"action"=>"Blah", "source_id"=>1}, ] } } 

Is it possible? Basically, I try to send two types of data at once ("page" and "link") and assign "source_id" from the "links" to the "id" on the page.

+6
ruby ruby-on-rails activerecord
source share
3 answers

Before sending to the database, you can write the code in the controller, which will take parameters and add other information before saving. For example:

 FooController < ApplicationController def update params[:page] ||= {} params[:page][:link_attributes] ||= [] params[:page][:link_attriubtes].each { |h| h[:source_id] ||= '1' } Page.create(params[:page]) end end 
+15
source share

You should probably also look at callbacks, namely before_validate (if you use validations), before_save or before_create.

It's hard to give you a concrete example of how to use them without knowing how you save the data, but it will probably be very similar to the example that Guy gave.

+2
source share

Edit parameters before using strong parameters

Ok, so (reviving this old question) I had a lot of problems with this, I wanted to change the parameter before it reaches the model (and retain the strong parameters). I finally figured it out, here are the basics:

 def update sanitize_my_stuff @my_thing.update(my_things_params) end private def sanitize_my_stuff params[:my_thing][:my_nested_attributes][:foo] = "hello" end def my_things_params params.permit(etc etc) end 
+2
source share

All Articles