Custom forms and fieldWithErrors tags


#1

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+’@'removed_email_address@domain.invalid_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


#2

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