ruby - Rails: Adding methods to ActiveRecord models -
i'm writing first rather simple ruby on rails (3.2) application. idea manage email accounts. schema rather simple:
t.string "email" t.string "password"
the activerecord model defined as:
class mailuser < activerecord::base attr_accessible :email, :password
i've been using scaffolding form_for(@mailuser)
, @mailuser.update_attributes(params[:mailuser])
magic. works well.
now quirk user should allowed edit user part (e.g. "foo") of email while domain (e.g. "example.org") must stay untouched. email field contains complete email address (e.g. "foo@example.org"). in edit form don't display fields
- password
but rather
- userpart
- password
where userpart
shown @mailuser.userpart
(editable) + domain (not editable).
so thought i'd solve adding getter , setter user part this:
class mailuser < activerecord::base attr_accessible :email, :password # getter user part (left of '@') def userpart email.split('@')[0] end # setter user part (left of '@') def userpart=(new_userpart) email = email.sub(/(.+)@/, new_userpart+"@") end
in fact getting @mailuser.userpart
works well. , it's displayed in form_for(@mailuser)
. problem occurs when saving form using @mailuser.update_attributes(params[:mailuser])
in controller's update
method. rails apparently tries update @mailuser
object attributes made available through attr_accessible
. userpart
attribute not reflect actual database field.
so wonder proper way add such methods activerecord models add functionality? i'm used pylons (a python mvc framework) , use such additional methods way.
(in fact wonder: can't split user , domain parts changing database schema. database used other applications i'm stuck way looks.)
thanks in advance.
you want add attr_accessible :userpart
userpart can updated update_attributes mass assignment.
added: userpart example of virtual attribute if want ask mr. google more detailed explanation.
Comments
Post a Comment