mysql - Rails 复杂 SQL

标签 mysql sql ruby-on-rails ruby-on-rails-3 activerecord

我有几个复杂的 SQL,需要将其转换为 ActiveRecord 查询。请帮助我:

我的模型:

class Product < ActiveRecord::Base
  belongs_to :watch, :counter_cache => true
end

class Watch < ActiveRecord::Base
  belongs_to :category
  has_many :products
end

class Category < ActiveRecord::Base

  has_ancestry :cache_depth => true, :depth_cache_column => :depth

  has_many :watches, :dependent => :destroy
  has_many :products, :through => :watches

end

所以类别有两层深度的祖先,根是 make,子级是 serie。 我的 SQL 如下:

scope :by_make, lambda { |make_name| Product.find_by_sql("
    SELECT p.* FROM products p INNER JOIN watches w ON p.watch_id = w.id
      INNER JOIN categories series ON w.category_id = series.id
      INNER JOIN categories makes ON series.ancestry = makes.id
      WHERE makes.name LIKE '%#{make_name}%'
    ") unless make_name.blank? }

 scope :by_series, lambda { |series_name| Product.find_by_sql("
      SELECT p.* FROM products p INNER JOIN watches w ON p.watch_id = w.id
        INNER JOIN categories series ON w.category_id = series.id
        WHERE series.name LIKE '%#{series_name}%'
      ") unless series_name.blank? }

请帮助将它们转换为 ActiveRecord 查询,因为不要在查询末尾获取数组非常重要,谢谢!

最佳答案

最简单的解决方案就是在 find_by_sql 的开头添加 where 过滤器,如下所示:

  scope :by_make, lambda { |make_name| where(:watch_id => Watch.find_by_sql("
    SELECT w.* FROM watches w
      INNER JOIN categories series ON w.category_id = series.id
      INNER JOIN categories makes ON series.ancestry = makes.id
      WHERE makes.name LIKE '%#{make_name}%'
    ")) unless make_name.blank? }

  scope :by_series, lambda { |series_name| where(:watch_id => Watch.find_by_sql("
      SELECT w.* FROM watches w
        INNER JOIN categories series ON w.category_id = series.id
        WHERE series.name LIKE '%#{series_name}%'
      ")) unless series_name.blank? } 

应返回 AR 集合。

关于mysql - Rails 复杂 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7093727/

相关文章:

php - 从 url 自动 zip 下载

php - 从 PHP 和 MySQL 中的 2 列创建关联数组

sql - SQL Server 2008 R2 上的自定义主键

ruby-on-rails - 设计:能够将参数传递给注册#sign_up 操作

ruby-on-rails - 私有(private) gem 没有安装在 docker 中

mysql - SQL返回属性不存在的连接的默认值

MySQL 死锁 - 访问不同的主键值也会造成死锁

java - 在内存数据库 h2 中保持连接打开多长时间?

sql - 如何获取 XML 节点的索引/位置

ruby-on-rails - 具有属性的 rspec stub any_instance