【问题标题】:Rails3 ActiveRecord and custom SQL JOINS with default_scopeRails3 ActiveRecord 和自定义 SQL JOINS 与 default_scope
【发布时间】:2012-09-18 15:04:19
【问题描述】:

我需要将一个不存在的表映射到 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

感谢任何指点。

【问题讨论】:

    标签: ruby-on-rails wordpress activerecord scope


    【解决方案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
    

    那么您应该可以在Category 上调用任何finder 方法,而无需自己实现。

    【讨论】:

      【解决方案2】:

      您是否会考虑创建Enterprise Rails 中所述的视图支持模型?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 1970-01-01
        • 2011-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多