Thursday, December 16, 2010

[Rails] Re: How does ActiveRecord translate parameter hash to values of a class instance's properties

John Merlino wrote in post #968948:
> Since User class inherits from ActiveRecord class, I presume
> ActiveRecord contains a constructor that takes the key/value pairs of a
> hash from the parameters of web form and checks if the keys of the hash
> match the instance methods available in current class instance which
> were generated from field names from a table of the same name (e.g.
> Users).
>
> Basically all that happening with this line:
> @user = User.new(params[:user])
>
> Hence, you can now do @user.login - should login be a field in the
> database. If a value for login was captured in the param hash, then
> @user.login will return value passed from params hash.
>
> Does anyone have a general description of what ActiveRecord does behind
> the scenes to achieve this?

You pretty much just described it. There's likely a good bit of
meta-programming happing behind the scenes, but as a general overview
what you describe is a good way to think about it.

If you really want to know then clone the Rails project and read the
code. It is open source after all.

> Now the second question. What about parameter's that are not part of the
> table field names? ActiveRecord doesn't create getter and setter methods
> for these parameters by default.
>
> You have to manually do it:
>
> attr_accessor :password #should a password field not exist in users
> table

You can think of attr_accessor, attr_reader, attr_writer as shortcuts
for writing out the individual accessor methods for dynamically
generated instance variables. No real magic is going on here other that
Ruby being dynamic and creating what it needs when it needs it at
runtime.

BTW: What you're describing here is often referred to as "virtual
attributes" when related to ActiveRecord. Everywhere else, AFAIK, they
are simply called accessors backed by instance variables.

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate