views:

199

answers:

2

I have two tables: keyword_reports and keywords (with relevant AR models).

keyword_reports has a keyword_id column, which I'm using to join the keywords table like so:

KeywordReport.find(:all, :joins => :keyword, :conditions => {:page_id => 10})

which correctly pulls back records for keyword_reports, but doesn't include the data from the joined keyword table.

I looked at the log to see the generated SQL and it is doing:

SELECT `keyword_reports`.* from...

instead of:

SELECT * from ...

which it needs to do in order for me to get all the data. When I manually edit the SQL to format as desired, sure enough, it grabs all the data. I've tried using :includes and :select to no avail.

How do I prevent the query from limiting results only to the first table?

A: 

Hi,

think you probably had a typo. :include (no s) should do it.

KeywordReport.find(:all, :include => :keyword, :conditions => {:page_id => 10})

This assumes that you have the relationship setup in the model

#KeywordReport
belongs_to :keyword

Hope this puts you one the right track

Jonathan
Hi,Thanks for your reply. The relationship is actually reverse. #Keyword has_many :keyword_reports #KeywordReport belongs_to :keywordBased on that, I don't think :include will help me. The generated SQL is two statements with the above suggestion, and they don't perform a join. The second statement just tries to find keyword records using the IN operator from keyword_id's returned from the keyword_reports result set.Perhaps I'm missing something so any further advice is appreciated.
Scott
A: 

Hello,

I had the same problem and solved it using:

:select => '*'

In my case this works, just be cautious of columns with the same name in the tables. I think only one of the columns will be available. To solve this you can use:

:select => '*, tbl1.field as field1, tbl2.field as field2'

Hope it helps.

jmgpena