Tue 12 Aug 2008
In a Rails system with a pretty standard user model, views, and controller, I recently found that the users_controller was getting pretty large. There was a pretty significant amount of code that I wanted to add to deal with the users using a different set of views under some circumstances — and I didn’t want to add all of that to the users_controller.rb. What I wanted was to move these functions to a staff_controller.rb, use restful routing on it and just treat the user object differently.
This didn’t work out so well initially. Trying to use form_for in a view always reflects on the type of object you have and sends the results right back to the users_controller — not what I wanted. I tried a bunch of stuff to force the form_for to do what I wanted but no joy. What I wanted I thought was a way to alias the user model.
class Staff < User end
Problem solved.
The User model had some nice named scopes for finders, for example:
named_scope
:recent,
:conditions => ["created_at > ?", 2.weeks.ago]
And now I can do all of the following
Staff.first
Staff.recent
Staff.find(params[:id])
@staff = Staff.recent.find(:all,
:conditions => ['name = ?',"jim"])
@staff.last_login_at = Time.now
@staff.save!
.. which since reflection now says they are staff objects, causes
all the view helpers that reflect on stuff to work properly and doesn’t
break any of the ActiveRecord stuff.