#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2005
    Posts
    321
    Rep Power
    13

    How to use ActiveRecord to retrieve all columns and rows... ?


    Hi, how can i use ActiveRecord associations to retrieve all columns and rows including the columns and rows in the referenced table.

    for example :

    Code:
    * = primary key
    + = foreign key
    
    Table : parents
    *id 
    parent_name
    
    Table : kids
    *id
    +parent_id
    kid_name
    
    class Parent < ActiveRecord::Base
       has_many :kids
    end
    
    class Kid < ActiveRecord::Base
       belongs_to :parents
    end
    How can I get all the columns present in this two table and produce something like:

    Code:
    parents.id, parents.parent_name, kids.id, kids.parent_id, kids.kid_name
    I only assume that the above ActiveRecord associations executes something like :

    Code:
    SELECT parents.id, parents.parent_name, kids.id, kids.parent_id, kids.kid_name
    FROM parents left join kids on parents.id = kids.parent_id
    Thanks
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,595
    Rep Power
    4207
    Something like this:
    Code:
    @array = []
    parents = Parent.find(:all)
    parents.each do |p|
       kids = p.kids
       kids.each do |k|
          # Do something with the data
          str = "#{p.id} #{p.parent_name} #{k.id} #{k.parent_id}"
          @array << str
       end
    end
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo