On Tue, Aug 01, 2006 at 11:33:57AM +1000, O Plameras wrote: > I have an MySQL statement as, > SELECT s.name,s.sex,p.city,s.state FROM students as s,states as p WHERE > s.state=p.state and s.id=4; > > And I have ActiveRecord statements that produce the same content as, > student=Student.find(4) > state=State.find(:first, :conditions=>['state=?',student[:state]]) > > As you can see I have two Ruby statements for a single MySQL statement. > > I know there are other ways to format the Ruby script to produce the same > results. > > My question is what is the common and standard way to do this? Is there > a better ActiveRecord-way to express this ? Will it be better with > foreign-keys ? Is there a single-statement-way to express this ?
Off the top of my head: class Student has_one :state, :foreign_key => 'state' end class State belongs_to :student, :foreign_key => 'state' end So then you can: s = Student.find(4) puts s.state.city If you rename the 'state' field in students to 'state_id', you can drop the :foreign_key bits of both above. BTW, your State table is terribly named. 'localities' or something might be more appropriate. - Matt _______________________________________________ coders mailing list [email protected] http://lists.slug.org.au/listinfo/coders
