[Rails] ActiveRecord and SQL SUM

Jarkko Laine jarkko at jlaine.net
Mon Jan 31 16:28:34 GMT 2005


Hi Joe,

How about making it a class method of the Guest class?

def self.guest_count
	connection.select_one("SELECT SUM(count) FROM guests WHERE  
guests.confirmed = 'y'")
end

http://rails.rubyonrails.com/classes/ActiveRecord/ConnectionAdapters/ 
AbstractAdapter.html#M000309

Then you could call it by Guest.guest_count.

//jarkko

On 31.1.2005, at 18:05, Joseph Martin wrote:

> I am a new Ruby / Rails user and I'm writing a small website to teach  
> myself
> both the language and the framework. I want to create a simple web  
> interface to
> the guest list for my upcoming wedding. I have two SQL tables: People  
> and
> Guests. The People table just has the usual name, address, telephone,  
> etc. The
> Guests table has a foreign key that links to People, a 'confirmed'  
> field and a
> 'count' field. I use the count field to store the number of additional  
> guests
> that will be coming to the wedding in addition to the named person.
>
> I want to be able to use the following query to find out how many  
> people are
> currently coming to the wedding: "SELECT SUM(count) FROM guests WHERE
> guests.confirmed = 'y'". How can I best express that query in Rails  
> with
> ActiveRecord? I know I can use a "data piggyback" in a model class,  
> but that
> does not seem appropriate. The model class represents one row in the  
> table. I
> think this query should go into some kind of object that represents  
> the table
> (or GuestList) as a whole. But I'm unsure of where to put it and how  
> to put it.
>
> Can anyone help me with this?
>
> Thanks,
>
> ~joe
>
>
> _______________________________________________
> Rails mailing list
> Rails at lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
--
Jarkko Laine
http://jlaine.net
http://odesign.fi
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2363 bytes
Desc: not available
Url : http://one.textdrive.com/pipermail/rails/attachments/20050131/a6d8fe36/smime-0001.bin


More information about the Rails mailing list