views:

47

answers:

2

If I say this in the controller:

@order = Order.new(params[:order])

What is required for this to work?

Does there need to be a one-to-one match between all of the fields in params[:order] and the Order model?

Or can there be more or fewer fields in params[:order] than are required to instantiate an Order?

+1  A: 

There can indeed be fewer fields.

Make sure you have all fields necessary for any validations though!

Reuben Mallaby
Could there also be more fields in the form than in the model? Would ActiveRecord just ignore the extraneous ones?
eggdrop
+1  A: 

params[:order] itself should be a hash, where each key is the name of the model field. To see how Rails converts form field names into the params hash, write a view template with the form_for helper and view source.

There can be more or fewer fields, yes. Extra fields will be ignored. Fewer fields just won't be copied into the instance object. You don't need anything at all to instantiate an ActiveRecord object. (Object validity and saving are a different story - they invoke validations and the ActiveRecord callback mechanism.)

Raphomet
Ok, so there's no problem instantiating the object - the problems you may encounter are when you try to save or update. In that case having fewer fields may violate a database requirement but not until then.
eggdrop
Yeah, exactly. Validations don't run until you save an object or call .valid? or .invalid. More here: http://guides.rubyonrails.org/activerecord_validations_callbacks.html
Raphomet