2011-06-25 41 views
2

我有以下SQL語句: SELECT article_id FROM publications WHERE category_id IN (SELECT id FROM categories WHERE parent_id = 3)ActiveRecord的: 「凡在」 SQL語句

如何將它轉換到Rails的ActiveRecord?我試過:Article.find(:all, :conditions => ["publications.category_id IN(?)", 3], :include => [:publications]),它返回空數組。

型號:

class Article < ActiveRecord::Base 
    has_many :publications 
    has_many :categories, :through => :publications 

class Category < ActiveRecord::Base 
    belongs_to :parent, :class_name => 'Category' 
    has_many :children, :class_name => 'Category', :foreign_key => :parent_id 
    has_many :articles, :through => :publications 
    has_many :publications 


class Publication < ActiveRecord::Base 
    belongs_to :article 
    belongs_to :category 
+0

您可以發佈您的關聯碼(的has_many,belongs_to的,等等)出版,文章和類別?我懷疑你可能在那裏出了問題。 – Yardboy

回答

3

這方面的工作?

Article.find(:all, 
      :conditions => ["publications.category_id IN(SELECT id FROM categories WHERE parent_id = ?)", 3], 
      :include => [:publications]) 

我會建議你使用ancestry代表在數據庫樹結構,也有a railcast about ancestry

+0

它的工作原理和感謝建議 – NARKOZ

+0

@narkoz我仍然希望看到你的模型,我認爲通過適當的關聯,你可以避免在你的條件下使用硬編碼的SQL。 – Yardboy

+0

@Yardboy我更新了模型的問題 – NARKOZ

0

做你的模型是什麼樣子?

您需要在文章,分類和發佈模型中正確設置關聯。

這聽起來像你有相關的外鍵在表中設置了,但你的模型不知道找該協會

+0

我不認爲這是正確的 - 基於SELECT語句,它在我看來像他的出版belongs_to:類別和類別has_many:出版物。需要看到他的協會。 – Yardboy

+0

剛剛看到,在10秒後得到我的編輯:) – ply

+0

10-4。糟糕,沒有刷新。 – Yardboy