SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
Thread: A tale of two tables
-
Mar 1, 2006, 20:11 #1
- Join Date
- Nov 2004
- Location
- Victoria BC
- Posts
- 116
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
A tale of two tables
I am just starting out in ror and I need a bit of help with two tables. I have a person and residence table with a residence_id field in the person table. I have the has_many, belong_to methods in the appropriate person and residence methds. What I want to do is list all the fields from both the person and corresponding address tables. I can list all the person data but I can't seem to list the residence data. Can someone give me an example of how to do thad so that I can display data such as person.streetname and person.housenum in a list view. I know it has to be easy but I have exhausted all the examples I have without success.
Rick
-
Mar 2, 2006, 09:06 #2
- Join Date
- Jun 2004
- Location
- California
- Posts
- 440
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Well lets say your belongs_to looks like this in your Person model:
Code:belongs_to :residence
Code:my_person = Person.find(:first, :include => :residence) my_person.residence.streetname my_person.residence.housenum
Code:class Person < ActiveRecord::Base ... def streetname self.residence.streetname end end
Code:class Person < ActiveRecord::Base belongs_to :residence delegate :streetname, :to => 'residence' delegate :housenum, :to => 'residence' end person = Person.find(:first, :include => :residence) person.housenum # same thing as: person.residence.housenum person.streetname # same thing as: person.residence.streetname
I <3 Rails
-
Mar 2, 2006, 14:40 #3
- Join Date
- Nov 2004
- Location
- Victoria BC
- Posts
- 116
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Thanks for that - I had the suspision that it had to be something simple. I amended your code to :
Code:my_person = Person.find(:all, :include => :residence)
Code:@person_pages, @persons = paginate :persons, :order_by => 'lastname, firstname', :per_page => 10
Rick
Bookmarks