Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: modify form parameters before modifying the database

I'm working on a Rails app that sends data through a form. I want to modify some of the "parameters" of the form after the form sends, but before it is processed.

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 this feasible? Basically, I'm trying to submit two types of data at once ("page" and "link"), and assign the "source_id" of the "links" to the "id" of the "page."

like image 901
Adam Rezich Avatar asked Jan 08 '09 19:01

Adam Rezich


3 Answers

Before it's submitted to the database you can write code in the controller that will take the parameters and append different 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
like image 104
Kevin Davis Avatar answered Oct 26 '22 21:10

Kevin Davis


Edit params before you use strong params

Ok, so (reviving this old question) I had a lot of trouble with this, I wanted to modify a param before it reached the model (and keep strong params). I finally figured it out, here's 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
like image 21
Mirror318 Avatar answered Oct 26 '22 22:10

Mirror318


You should also probably look at callbacks, specifically before_validate (if you're using validations), before_save, or before_create.

It's hard to give you a specific example of how to use them without knowing how you're saving the data, but it would probably look very similar to the example that Gaius gave.

like image 24
arjun Avatar answered Oct 26 '22 21:10

arjun