Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help w/ pulling data from 2 tables and displaying the results

Status
Not open for further replies.

clemcrock

Programmer
Dec 17, 2006
63
US
Hello,

I'm brand new to ruby and I'm having trouble pulling data from one
table (table_1), looping through the results and pulling data from
another table (table_2) and displaying the results of table_2 in one
field.

The 2 tables I have are accounts and spaces. The accounts table will
have many spaces connecting the 2 tables by the foreign key user_id.

so I tried my 2 model declarations as follow:

Code:
class Account < ActiveRecord::Base has_many :spaces end class Space < ActiveRecord::Base belongs_to :account end
Then I try to call the 2 tables w/ this:

Code:
@accounts = Account.find(:all, :include => :spaces )

Then I get this error:

Unknown column 'spaces.account_id' in 'on clause':

Somehow - it was getting the idea that account_id was the foreign key so
I did this:

Code:
class Account < ActiveRecord::Base has_many :spaces, :class_name => 'Account', :foreign_key => "user_id" end class Space < ActiveRecord::Base belongs_to :account, :class_name => 'Space', :foreign_key => "user_id" end

and now I get this error: undefined method `loaded'

Most frustrating!
 
Ok - I finally buckled down and asked a couple of questions and there
was a method in the accounts model that was killing this whole concept:

The project I'm building a little addition to is huge and extremely complex so there's a lot of code that could overide or clash w/ code I'm trying to develop.

That was the case here. In the Account model there was this method that was overiding my join attempts.

def spaces
spaces = Space.find :all, :conditions => ['owner_id = ?',
self.user_id]
end

Now, once I got rid of that method - this works perfectly!
@accounts = Account.find:)all, :include => :spaces, :limit => 20)

I got dumped right into the fire w/ this new project - it pays to ask a few simple questions. I tore a lot of hair out trying to figure it out, but also learned a great deal trying to find the answer.

posts!

Cheers!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top