I have first_name
and last_name
fields currently represented in my model in rails. I'd like to add another field to my database called full_name
and was wondering what the best way to do this seamlessly would be. Mind you I also have a production server going and would like to make it so that I not only add a column in my migration, but also can populate the new field with the existing data.
EDIT:
Here's my controller
def followers
@title = "Followers"
@user = User.find(params[:id])
@users = @user.followers.paginate(page: params[:page])
@followers = @user.followers.find(:all, :select => 'users.id, users.first_name, users.last_name', :conditions => ["users.first_name like ?","%" + params[:q] + "%"])
respond_to do |format|
format.html {render 'show_follow'}
format.json {render :json => @followers}
end
end
I want to be able to 1. select: 'users.id, users.full_name
and 2. :condition =>["users.full_name like ?", ...]
and the only way I can think to do this is to modify the model. I also only want to return the properties id
and full_name
in the json object.
You will probably be better off just defining a full_name method in your model:
def full_name
([first_name, last_name] - ['']).compact.join(' ')
end
You can search by full name with something like:
def self.find_all_by_name_containing(text)
self.where("LOWER(first_name || ' ' || last_name) LIKE ?", "%#{text.downcase}%")
end
Then define your own #to_json
If you really want to go ahead with adding a full_name
field to your User
model, then I suggest the following steps.
1.Generate a rails migration adding the field full_name
to users
table.
rails g migration add_full_name_to_users full_name:string
2.Add the following before_save
callback to your User
model.
Class User < ActiveRecord::Base
...
before_save :set_full_name
private
def set_full_name
self.full_name = "#{self.first_name} #{self.last_name}".strip
end
end
3.Commit, push code to production, run migration on production.
4.Run a save
or save!
method on all your users in rails console.
$> User.find_each(:batch_size => 1000){ |user| user.save }
I guess, that should take care of updating your existing users, plus the before_save
call will take care of future additions/updates.
Generate migration
rails g migration add_full_name_to_users
Inside migration:
def up
add_column :users, :full_name, :string
execute <<-SQL
UPDATE users SET full_name = first_name||' '||last_name WHERE full_name IS NULL;
SQL
end
It will create full_name column and populate it with default data. You can also do something like this in ruby but it will be much faster in SQL.