Question

Relative newbie here to Ruby on Rails.

Using the standard form_for method in the view for my SomeobjController#new action

= form_for @someobj do |f|
    .
    .
    .
  %p.submits
  = f.submit "Submit", :class => "submit"

a submission param[] array is produced that contains a hash of @someobj for all the fields set in the form, such that

param[someobj] => { "field1" => "val1", "field2" => "val2", ... }

I would prefer to put a different value, the result of someobj.to_s to param[someobj] for the SomeobjController#create to work with, such that

param[someobj] => "strvalfromtos"

I doubt it's relative, but just in case, the model underlying this #new action is not persistent in the database (i.e., Someobj is not derived from ActiveRecord::Base, though some portions of ActiveModel are included.)

I haven't had luck trying to adjust this until after #create is invoked, but its the submission from #new to #create that I want to amend. It's not clear to me if I should be focusing more on the form_for statement or doing something special in the controller (I'm guessing the form_for is the right focus).

And, yes, this whole thing is probably a bit OCD of me, but the actual fieldnames are long (appropriately for the model) but data needed by #create is very small.

Is there a relatively painless way to do this, assuming that someobj.to_s has already been written?

Many thanks, Richard

Was it helpful?

Solution

Change

When you submit the form, your controller will receive the params hash, as you've stated (Rails params explained?)

That means you can change any value in the hash that you wish:

def create
    #has access to the params hash
    params[:owner][:key] = value
end

As the create method receives the hash object, you'll have to change it in here. But because it's a standard hash (which has already been declared), you should be able to alter it as required

Add

If you want to add values to the params hash, you can use the .merge method, like this:

def create
    #has access to the params hash
    params[:key].merge(user_id: current_user.id)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top