Posted by Randy
on October 02, 2009
I was poking around while working with creating an application specifically for web services. We decided to use JSON as the methods of transportation of data, but the problem came when I wanted to include custom methods, or associations in my data set. The solution was fairly simple, using the to_json method.
Suppose you have the following classes:
class Client < ActiveRecord::Base
has_many :employees
end
class Employee < ActiveRecord::Base
belongs_to :client
def full_name
"#{first_name} #{last_name}"
end
end
We want the controller to return a client with association employees and the full name in the database. Here is how we would go about doing that:
def show
@client = Client.find(params[:id])
respond_to do |format|
format.json { render :json => @client.to_json(
:include => {
:employee => {
:only => :email,
:methods => [ :full_name ]
}
}
) }
end
end
You will end up with the following data set:
{ client: { name: "Some client", employee: { email: "test@test.com", full_name: "John Doe" } } }
Forgive me if I messed up the json output…doing it from memory
There are of course way easier uses for this too, but I just decided to spit out a more complex one.
Posted by Randy
on October 22, 2008
The other day I had to display the number of children items an object had so I decided to do the following:
# Controller
@customers = Customer.find(:all, :include=>[:receive_payments])
#View
<%= customer.receive_payments.count %>
While this worked for what I needed, it executed the following sql every iteration:
SELECT count(*) AS count_all FROM "receive_payments" WHERE ("receive_payments".customer_ref_list_id = E'850000-1071531366')
I thought this wasn’t right considering I used an association, however when you use count, it forces the use of count(*) on the database. This is where size comes in!!!!
<%= customer.receive_payments.size %>
Now we get the same results without the extra database counts!
Posted by Randy
on August 29, 2008
I’m sure you all know how to use the :conditions attribute when using ActiveRecord:
User.find(:all, :conditions=>['active = ?', true])
And you may even use associations this way:
User.find(:all, :include=>[:photos], :conditions=>['photos.removed = ? and users.active = ?', false, true])
But did you know that you can do this easier through hashes?
User.find(:all, :conditions=>{:active=>true})
User.find(:all, :include=>[:photos], :conditions=>{'photos.removed'=>false, 'users.active'=>true})
Nothing special there, but I thought it was pretty cool. One thing you have to remember when using associations, is to include that model.