2012-09-18 65 views
2

我需要將一個不存在的表映射到ActiveRecord(在我的情況下:Wordpress數據庫模式),它由一個自定義SQL語句組成,如下所述。我希望能夠在其他語句中使用find(),first(),all()。有沒有一種方法可以在不覆蓋所有查找器方法的情況下完成此操作? (我目前正在重新定義這些方法,來實現類似的結果,但很想知道是否有一個更ActiveRecord的/ Rails的方式這樣做)Rails3 ActiveRecord和自定義SQL JOINS with default_scope

目前我在做什麼,例如

class Category < ActiveRecord::Base 
    self.table_name="wp_terms" 
    def self.all 
    Category.find_by_sql("select distinct(wp_terms.term_id),wp_terms.name,wp_term_taxonomy.description,wp_term_taxonomy.parent,wp_term_taxonomy.count from wp_terms inner join wp_term_relationships ON wp_term_relationships.object_id = wp_terms.term_id INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_id = wp_terms.term_id where taxonomy = 'category';") 
    end 
end 

感謝任何指針。

回答

1

您可以使用default scope

class Category < ActiveRecord::Base 
    self.table_name="wp_terms" 

    # Individual scopes for readability - the names could be improved. 
    scope :select_scope, select("DISTINCT(wp_terms.term_id), wp_terms.name, wp_term_taxonomy.description, wp_term_taxonomy.parent, wp_term_taxonomy.count") 
    scope :join_scope, joins("INNER JOIN wp_term_relationships ON wp_term_relationships.object_id = wp_terms.term_id INNER JOIN wp_term_taxonomy ON wp_term_taxonomy.term_id = wp_terms.term_id") 
    scope :where_scope, where("taxonomy = 'category'") 

    default_scope select_scope.join_scope.where_scope 
end 

那麼你應該能夠調用任何finder方法上Category,而無需實現它自己。