views:

1210

answers:

2

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."

+10  A: 

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
Kevin Davis
Anything more specific?
Unniloct
I can't vote up the example by Gaius.. but yeah, that
Kevin Davis
No, but oddly I can upvote your answer that I edited.
James A. Rosen
@Gaius: That's a potential exploit of stackoverflow :P
Yaser Sulaiman
D: Thanks for the better example, though.
Unniloct
+1  A: 

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.

arjun