0

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
1
  • If it's coming from a form you should be able to pass in params[:my_model] or whatever it's sending. If you can't, that means that you're not using the Rails form/form fields, or aren't naming them properly. Either that, or you should use a form model containing only the fields you need. Commented May 30, 2013 at 16:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

In this case, use form helpers (form_for)
if I can't use form_for, is there any way to simply my code, for example, by using reflection or something like that?
If you can't use form_for, that shouldn't prevent you from still adhering to rails conventions, i.e if you use text_field_tag, you can still arrange for the input element name to be 'my_model[field1]'

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.