Rails Against The Machine

Just a mind dump. Why are you even reading this?

Wednesday, 26 November 2008

 

Complex active record associations

First up custom finders/counters
has_many :photos,:class_name => 'Picture',
:finder_sql => '
SELECT pictures.*,
FROM pictures
WHERE pictures.code = \'#{code}\'
ORDER BY pictures.order,
:counter_sql => 'SELECT COUNT(*)
FROM pictures
WHERE pictures.code = \'#{code}\'


Three things which might trip you up
(1) counter_sql may need to be specified if your select is complex since by default it replaces the select caluse of the finder_sql with a simple count.
(2)use single quotes
(3)#{code} are active record attributes corresponding to column names you cannot use method names here

Now adding methods to the association

in your class where you declare has_many :pictures

class User < ActiveRecord::Base

has_many :pictures do

def custom_function
foo
end

private
def foo
self << 'foo'
end
end
end
so now you can do something like

p=User.new
p.pictures.custom_function

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

Archives

July 2007   August 2007   September 2007   December 2007   January 2008   February 2008   March 2008   April 2008   June 2008   July 2008   August 2008   October 2008   November 2008   January 2009  

This page is powered by Blogger. Isn't yours?

Subscribe to Comments [Atom]