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
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
onchangeeventfirst_nameandlast_nametext field.Or you can do it on server side in your model, e.g:
before :saveis executed each time when you’re update your modelAnyway 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:
this SQL code might be database dependent, if you’re using MySQL it’s probably ok