I need to map a non-existing table to ActiveRecord (in my case: the WordPress Database Schema), which consists of a custom SQL statement as described below. I want to be able to use find(), first(), all() among other statements. Is there a way to accomplish this without actually overwriting all the finder methods? (i am currently redefining those methods, to accomplish similar results, but would love to know if there is a more ActiveRecord/Rails way to do so)
currently i am doing for example
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
thanks for any pointers.
You can use a default scope:
Then you should be able to call any finder method on
Category
without having to implement it yourself.Would you consider creating a view-backed model as outlined in Enterprise Rails?