我需要将一个不存在的表映射到ActiveRecord(在我的例子中:Wordpress数据库模式),它由一个自定义SQL语句组成,如下所述。我希望能够使用 find()、first()、all() 以及其他语句。有没有办法在不实际覆盖所有查找器方法的情况下完成此操作?(我目前正在重新定义这些方法,以实现类似的结果,但很想知道是否有更多的 ActiveRecord/Rails 方法可以做到这一点)
目前我正在做例如
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
感谢您的任何指示。
您可以使用默认范围:
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
然后,您应该能够在Category
上调用任何查找器方法,而无需自己实现它。
你会考虑创建一个 Enterprise Rails 中概述的视图支持的模型吗?