Forum: Ruby on Rails Custom forms and fieldWithErrors tags

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7b56484f1e9d9af7b4c2c7ef16142197?d=identicon&s=25 Martin Boese (Guest)
on 2006-02-21 14:15
(Received via mailing list)
Hi,

(probably) A newbie questions:

I have a form where a user can choose an email address, but there are
only
some choices for the domain, so I wrote a helper where the local part of
the
email is a text field and the domains is a dropdown list, like:
Select Email:  [  my_name    ] @ <domain.com>

..which I defined as a helper:

def email_form(tagname, domain_list)
  text_field(tagname,"local_part", :size => 15) + " @ " +
        select(tagname, "domain_part", domain_list)
end

In the database however I only have one email_address textfield which is
the
full email address.
To get that done I added two attr_accessor's for local_part and
domain_part,
so I can store the information from the forms, and some checks:

Model (part of it):

 attr_accessor :local_part
 attr_accessor :domain_part
 validates_presence_of :local_part, :on => :create
 validates_format_of :local_part, :with =>
         /^[_\.-abcdef..(cut)...890]+$/, :on => :create

 def validate_on_create
   em = Mail.find_by_email_address(email_address)
   errors.add :local_part, 'Email already taken' if !em.nil?
 end

... and then compose the real email address in the controller on the
submit
action, like:

Controller:
   @email = Mail.new
   @email.attributes= @params['email']
   @email.email_address = @email.local_part+'@'+@email.domain_part

This is working so far, but what bothers me .. and I am sure there is a
better
solution:

1st: I have to compose the 'real' email_address manually on form submit
in the
controller, how can I get this done in the model?

2nd: The error div-tags waste up my helper as they surround the
local_part
only which create a newline. Will look like:
[ my_email ]
@ <domain.com>

3rd: I think the model will end-up to specific on the create event. All
further operation the email address can not be changed anymore.. not
nice
imo..

Thanks for any help/advice..

Martin
C56f6508ce4610e8527606a435b5870f?d=identicon&s=25 William (Guest)
on 2006-02-21 19:39
> 1st: I have to compose the 'real' email_address manually on form submit
> in the
> controller, how can I get this done in the model?
>

In your model try using the before save filter

before_save :set_email

def set_email
   self.email_address = @self.local_part+'@'+self.domain_part
end

That's the idea. That's off the top of my head so it may need some
tweaking
This topic is locked and can not be replied to.