I have a user model with attributes first_name, last_name and email.
In the view I’m looping though all the users and for each user
printing out the email add the full_name (full_name is a function in
the user model that returns both first and last names). The email
prints but the names do not and it’s really weird. I have checked in
the script/console and verified that the values are actually inside
the user object (I only have one user object created with the
migration).
What’s even weirder is that when I call User.find_by_email “blah” and
it gives me back my user, the output in the console shows all the
fields, shows the first_name and last_name values as well. But in the
console if I do u.first_name, I get a nil return. If I do u.email, I
get the “blah” return. Any idea where I can start looking for a
problem?
Parameters of a model aren’t assigned to instance variables, they’re
accessed through method calls. So drop the “@” signs. While you’re at
it, you can get rid of the string concatenation:
def full_name
[first_name, last_name].join(" ")
end
…now, if you’re missing a first or last name, you don’t get extra
white-space padding (and if you want to include ‘title’ or
‘middle_name’ you’re not creating n+1 strings).
def full_name
[first_name, last_name].join(" ")
end
…now, if you’re missing a first or last name, you don’t get extra
white-space padding (and if you want to include ‘title’ or
‘middle_name’ you’re not creating n+1 strings).
After I got rid of the ‘@’ part they were still returning nil. I had an
attr_accessor :first_name, :last_name defined. Things worked after
getting
rid of that. I guess having attr_Accessor with the same names overrides
the
method calls or something?
After I got rid of the ‘@’ part they were still returning nil. I had an
attr_accessor :first_name, :last_name defined. Things worked after getting
rid of that. I guess having attr_Accessor with the same names overrides the
method calls or something?
You don’t need attr_accessor for attributes from the database -
attr_accessor will overwrite (or prevent the generation of) the
accessors active record provides.
from iPhone away from irb right now, so can’t verify).
100% correct… sorry - my real methods do compact before the join…
just not when I write them in Gmail!
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.