I have a Rails model called Person which has database table columns for first_name and last_name. I’ve also defined a full_name method to return the combined first_name and last_name of the instance.
Is there a way to return an array, hash, or object which has first_name, last_name, as well as full_name?
Here’s the code I have:
#person.rb
class Person < ActiveRecord::Base
validates_presence_of :first_name, :last_name
def full_name
self.first_name + " " + self.last_name
end
end
Here’s what I’ve tried in the Rails console:
ruby-1.8.7-p302 > person = Person.new({:first_name=>"Bruce", :last_name=>"Wayne"})
=> #<Person id: nil, first_name: "Bruce", :last_name: "Wayne", created_at: nil, updated_at: nil>
ruby-1.8.7-p302 > person.save!
=> true
ruby-1.8.7-p302 > Person.last
=> #<Person id: 1, first_name: "Bruce", :last_name: "Wayne", created_at: "2010-11-09 22:53:14", updated_at: "2010-11-09 22:53:14">
Is it possible to get something returned like this instead:
ruby-1.8.7-p302 > Person.last
=> #<Person id: 1, first_name: "Bruce", :last_name: "Wayne", :full_name: "Bruce Wayne", created_at: "2010-11-09 22:53:14", updated_at: "2010-11-09 22:53:14">
Or can it only return values from the database?
Eventually, I’d like to be able to call Person.all to return an array of hashes which also includes full_name.
Thanks in advanced!
The
first_nameandlast_nameare DB attributes which are printed in the inspect method.If you want to access the
full_namecallfull_nameon the user object.So if you want a hash of users with
full_nameas key:Edit 1
The
User.lastcall returns anUserobject. What gets printed in the console depends upon how the inspect method on the object is implemented. In case of ActiveRecord, database attributes are printed.If you need the full name, you need to call the
full_namemethod on the returned User object.I am still not clear what you are trying to do.
Edit 2
Edit 3
If you want to get a JSON format out of an object do the following
Refer to the
to_jsondocumentation for more details.Edit 4
The to_json method has
includeandexcludeoptions for you to select the attributes you need. The to_json method gives you total control over data selection. Refer to the documentation link above for more details.If you need to include additional attributes, add them to the
:includearray in the above example.Edit 5
To use this along with respond_with do the following: