I have the following rails model:
class Customer < ActiveRecord::Base
attr_accessible :firstname, :lastname, :email, :phonenumber, :company_id
def name
"#{self.lastname} #{self.firstname}"
end
scope :search_by_name, lambda { |q|
(q ? where(["firstname LIKE ? or lastname LIKE ? or (firstname || ' ' || lastname) like ?", '%'+ q + '%', '%'+ q + '%','%'+ q + '%' ]) : {})
}
end
I retrieve a JSON object of that model via ajax.
The problem is that i want to access the name attribute in my autocomplete text field (I don’t want to combine firstname and lastname in one database field).
Does somebody now how to access the name attribute in javascript or how to send the name attribute in the json object? (and which method is best)
When your controller renders the json you can specify what to send. By overriding the default json sent you could specify the name.
Something along the lines of:
Or you could look into using a json builder like https://github.com/rails/jbuilder if you intend to have more complex json being sent.