开发者

ActiveRecord find through has_one association child attribute

开发者 https://www.devze.com 2023-01-08 04:10 出处:网络
I have models like this: c开发者_运维知识库lass Discussion < ActiveRecord::Base has_many :comments

I have models like this:

c开发者_运维知识库lass 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!


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消