On Jun 26, 2:00 am, "ryan bayona" <
ryanbay...@gmail.com> wrote:
> Hi,
> Just new to Rails,, and i have some questions :
Welcome!
> How can i use ActiveRecord associations to retrieve all columns and rows
> including the columns and rows in the referenced table.?
>
> *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
> *
> In PHP in can retrieve all rows returned by this query from all joined
> tables using mysql_fetch_array() and the output is
> *
parents.id, parents.parent_name,
kids.id, kids.parent_id, kids.kid_name*
>
> Is there an equivalent of this in RoR?
This is one of the changes in thinking when we switch to Rails. The
belongs_to and has_many lets us not worry about the underlying queries
too much.
For example, if the goal is to get a list of kids given a parent, then
it's this easy:
parent = Parent.find(1) # 1 is the parent_id, use whatever you want
parent.kids.size => returns the number of kids
parent.kids.first.kid_name # returns the name of the first kid
Another example:
kids = Parent.find(1).kids # get all kids for the parent
names = kids.collect { |kid|
kid.name } # names is now an array of
names
You may also want to take a look at "Rails for PHP Programmers" by
Pragmatic Press.
Hope this helps?
Jeff
softiesonrails.com
purpleworkshops.com
> Here is the AR Associations that i want to retrieve all columns including
> those belonging to the referenced table
>
> *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*
>
> Thanks!