I would like to create rake task to set the username of all users' without 
a username to the part before the '@' in their email address. So if my 
email is [email protected], my username should become test. If it's not 
available, prepend it by a number (1).

So i have problem witch checking uniqness of username. Code below isn`t 
working after second loop ex: when i have three emails: [email protected], 
[email protected], [email protected] username for [email protected] will be empty.

I have of course uniqness validation for username in User model.

    desc "Set username of all users wihout a username"
    task set_username_of_all_users: :environment do
      users_without_username = User.select{ |u| !u.username? }
      users_without_username.each do |user|
        username = user.email.split('@').first
        if User.find_by_username(username).blank?
          user.username = username
          user.save
        else
          User.find_by_username(username).each_with_index do |u, index|
            u.username = username.insert(0, index)
            u.save
          end
        end
      end
    end

Other ideas are in Gist: https://gist.github.com/3067635#comments

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/rubyonrails-talk/-/4tkg3bBKTbcJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en-US.

Reply via email to