12

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

3 Answers 3

19

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
Sign up to request clarification or add additional context in comments.

Comments

11

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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.