How do you automatically map "params" onto an object?

Disclaimer: Ruby/RoR nuby

How do I automatically map my "params" object onto a model object from within my controller?

Thanks, Jason

Pretty nubish here too. If you look at scaffold methods, it will give you a hint. ActiveRecord objects can be mapped to a hash, and your params is just a hash, so if your params has within it a 'user' key containing a hash with 'username', 'password', 'phone', etc, you can do User.new(params[:user]), which is the same as doing User.new(:username => 'billj', :password => 'billrules', :phone => '123-456-7890') Thanks, Jason

Jason Vogel wrote:

I was hoping to use a generic approach and not have to specific each field [column].

Does any body know of a generic way to do this and handle "extra" parms?

Thanks, Jason

The answer lies within the scaffold code, have you tried generating a scaffold for a model and looked at it?

The main trick here is to match the params keys to the field names in your database.

For example:

--DB   create table comments     title varchar(50)     text varchar(255)   end

--view   form_tag :controller => 'comments', :action => 'add'     text_field('comment', 'title')     text_area('comment', 'text')     submit_tag "Add Comment"   end

--Comments Controller   def add     Comment.create(params[:comment])   end

I think I understand:

If the params hash has keys that do not match the database fields you will end up with "method not found" type errors.

I have been looking for a neat way around this issue. I suspect the answer will come from the "method_missing" hook, but this may cause genuine errors to fail silently...

Doh! of course!

It never occurred to me to put all the model specific values into their own array on the form, which solves the "method_missing" errors.

In your model:

attr_accessor :foo