Rails3 ActiveRecord and custom SQL JOINS with default_scope

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

Read More
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.

Related posts

Leave a Reply

2 comments

  1. You can use a 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
    

    Then you should be able to call any finder method on Category without having to implement it yourself.