views:

67

answers:

2

I have models like this:

class Discussion < ActiveRecord::Base
  has_many :comments 
  has_one :special_comment, :class_name => "Comment"
end

class Comment < ActiveRecord::Base
  belongs_to :discussion
  # contains author
end

How can I select every Discussion through its adjoined :special_comment 'author' association. Effectively I want to do something like:

select * from discussions 
inner join comments on comments.discussion_id=discussion.id 
where comments.author = 'poopface'

I get something close with this:

Discussion.find(:all, :conditions => {:author => 'poopface'}, :joins => :special_comment) ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: discussions.author: SELECT "discussions".* FROM "discussions" INNER JOIN "comments" ON comments.discussion_id = discussions.id WHERE ("discussions"."author" = 'poopface')

But it should be WHERE ("comments"."author" = 'poopface')

Thanks!

A: 

Assuming you have some foreignkey on your Comments table that your has_one is referencing...

Discussion.find(:all, :conditions => {:comments=>{:author => 'blah'}}, 
                    :joins => :special_comment) 

will give you all Discussions where special_comment is authored by 'blah'.

Discussion.find(:all, :conditions => {:comments=>{:author => 'blah'}}, 
                    :joins => :comments) 

will give you all Discussions where they have any comments authored by 'blah'.

Nigel Thorne
This will throw a SQL error. The hash key `special_comment` is used as the table alias for `discussions` table, by the `find` call. The table alias for the `discussions` table is `discussions`. This is a known limitation while using nested hash for conditions.
KandadaBoggu
fair point.. It should be 'comments' then.. special_comment is a reference to a comment not a discussion. - I believe.
Nigel Thorne
You are right, `special_comment` refers to `comments`.
KandadaBoggu
A: 

Try this:

Discussion.all(:conditions => {:comments=> {:author => "blah"}}, 
          :joins => :comments)

OR

Discussion.all(:conditions => ["comments.author = ?", "blah"], 
          :joins => :comments)

Note: May be you could have used a better author name in your sample code.

KandadaBoggu
Updated the answer after fixing an error.
KandadaBoggu