Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Save full_name method to database

I'm trying to save the full_name method to the database during initial registration. For proper searches I need to be able to query full_name in the db rather than just displaying it...

This is what the method looks like now:

/models/user.rb

 def full_name
   first_name + " " + last_name
 end

(Assume I already created a :full_name column to my User table.) I know I'm going to need some sort of callback - should I be using before_create or after_create? And then how would I actually insert the product of the method into the db?

Thanks!

Zander

2 Answers

Jason Seifer
STAFF
Jason Seifer
Treehouse Guest Teacher

Hey Alexander,

If you're trying to query based on both fields, you can always do a find like so:

User.where("first_name = ? and last_name = ?", first_name, last_name)

Where first_name and last_name are variables that have already been set somewhere else.

In order to save the product of a method to the database, you'd need to create a full name column in a migration and set it programmatically (assuming you already have first/last name set):

before_save :set_full_name
def set_full_name
  self.full_name = "#{@first_name} #{@last_name}"
end

Thanks Jason!

This makes perfect sense. I'm incorporating the search tutorials from railscasts, and this makes them work great.