2012-09-18 61 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,而无需实现它自己。