Alan Coromano
Alan Coromano

Reputation: 26018

Passing params for creating and updating a model

I wonder, is there an easier way to do the following

#controller's action
@my_model = MyModel.create field1: params[:field1],
               field2: params[:field2],
               field3: params[:field3],
               field4: params[:field4]
               # and so on.....

I would use

  @my_model = MyModel.create params

but would it work since params always contains other keys added by Rails?

P.S. The same question for updating a model (would this work properly?)

MyModel.update_attributes params

Upvotes: 0

Views: 61

Answers (1)

user946611
user946611

Reputation:

Send params as a nested hash like

{:my_model => {:field1 => 'blah', :field2 => 'blah'}, :controller => 'something', :action => 'something_else'}

This way you could just say

@my_model = MyModel.create params[:my_model]

Rails does this automatically if you have followed the conventions while creating the form.

Upvotes: 1

Related Questions