user1720381
user1720381

Reputation:

Ruby on Rails: Concatenate two pieces of data into one column

I have 3 columns in my table projects. first_name, last_name, and fullname.

<%= f.hidden_field :first_name, :value => current_user.firstname %>
<%= f.hidden_field :last_name, :value => current_user.lastname %>

At the moment when the user saves a project, the first name and last name of user get saved into separate columns. I am now wanting for both the first name and last name to get saved to a column full name, so I can search on them later.

So if the name was

first_name = "Joe"
last_name = "Bloggs"

How would I get

fullname =  "Joe Bloggs"

I tried this, but it doesn't work.

<%=f.hidden_field :fullname, :value => :first_name + :last_name %>

Can someone point me in the right direction? I'm new to rails so please remember this when trying to help. Thanks.

UPDATE

Now I have added this to my project model:

def set_fullname
    fullname = first_name + last_name
  end

and I now call this in my view:

<%= f.hidden_field :first_name, :value => current_user.firstname %>
<%= f.hidden_field :last_name, :value => current_user.lastname %>
<%= f.hidden_field :fullname, :value => @project.fullname %>

When I hit submit, and I check the logs the first and last names get saved to the table as usual, but the full name goes in blank. Can anyone see what the problem is?

UPDATE2

View:

<%= f.hidden_field :first_name, :value => current_user.firstname %>
<%= f.hidden_field :last_name, :value => current_user.lastname %>
<%= f.hidden_field :fullname, :value => @project.set_fullname %>

Project Model:

def set_fullname
    fullname = first_name + last_name
  end

When I try to access the page I get this error.

undefined method `+' for nil:NilClass

Upvotes: 2

Views: 8760

Answers (2)

Horacio
Horacio

Reputation: 1974

I know this was already answered by Tombart, but this could help someone else.

class Person

  before_create do
    self.fullname = "#{first_name} #{last_name}"
  end
end

You can find more info on RailsGuides.

Upvotes: 0

Tombart
Tombart

Reputation: 32466

Ruby code in your view is executed when the form is loaded, by that time there is no content in the form (if you create a new record). It would make sense to write similar code in javascript an map it to onchange event first_name and last_name text field.

Or you can do it on server side in your model, e.g:

class Person

  before :save, :set_fullname

  def set_fullname
    fullname = "#{first_name} #{last_name}"
  end
end

before :save is executed each time when you're update your model

Anyway much cleaner solution would be to adjust your search query, this way you just duplicate information in your database.

While searching try something like this:

"first_name LIKE ? or last_name LIKE ? or concat(last_name, ', ', first_name) LIKE ?"

this SQL code might be database dependent, if you're using MySQL it's probably ok

Upvotes: 7

Related Questions