1
votes

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!

2
What is the has_one using to identify the 'special_comment' rather than the other comments? has_one is used instead of belongs_to where your foreign key is on the other object. Is this your situation?Nigel Thorne

2 Answers

2
votes

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.

0
votes

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'.