Ror noob need help with easy hidden_field question

I’m trying to save users the trouble of creating a username, so I am
generating it based on their email address. It doesn’t need to be
unique, it is used in the view only, but that’s not my question.

My question is how do I store it when the user fills out the form?
Obviously, this won’t work, bc the user’s email isn’t saved yet…any
help you can provide? The line in ******* is the problem. Thank you.

- form_for resource_name, resource, :url =>

registration_path(resource_name) do |f|
= f.error_messages

    = f.label :email
    = f.text_field :email

    = f.label :password
    = f.password_field :password

    = f.label :password_confirmation
    = f.password_field :password_confirmation

************* = f.hidden_field_tag(:username,
@user.email.split(’@’,2).first) ***********************

    = f.submit "Sign Up"
 = f.error_messages

************* = f.hidden_field_tag(:username,
@user.email.split(’@’,2).first) ***********************

   = f.submit "Sign Up"

Why do you need to put it into the form? Seems like this would be a
good spot for a before_save handler in your user model. Check to see
if the :username field is blank and if so, set it to the first bit of
the email address…

-philip

Philip H. wrote:

Why do you need to put it into the form? Seems like this would be a
good spot for a before_save handler in your user model. Check to see
if the :username field is blank and if so, set it to the first bit of
the email address…

-philip

Thanks! before_save worked great!

code for others:

class User < ActiveRecord::Base
before_save :create_username
private

def create_username
self.username = self.email.split(’@’,2).first
end

end

Sioux Sioux wrote:

code for others:

class User < ActiveRecord::Base
before_save :create_username
private

def create_username
self.username = self.email.split(’@’,2).first
end

end

So what happens when [email protected] and [email protected] both sign up?
Perhaps you should just use the whole address.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs