复杂的Sql查询到RoR ORM

时间:2014-10-27 15:40:38

标签: mysql ruby-on-rails ruby-on-rails-4 orm

我有一个非常复杂的SQL查询,我想将其转换为RoR的ORM。

SELECT c.* FROM (SELECT companies.* FROM companies WHERE city = "?" AND country = "?") AS c INNER JOIN tagsForCompany AS tc ON c.id = tc.Company INNER JOIN tags AS t ON t.id = tc.TID WHERE t.Name REGEXP '?'

我已经定义了这样的模型:

companies.rb

class Company < ActiveRecord::Base
    # ... Some code that doesn't matter 
    has_and_belongs_to_many :tags
    # ... Some other code 
end

和tags.rb

class Tag < ActiveRecord::Base
    has_and_belongs_to_many :company
end

我需要公司控制器中的一个功能,用于搜索上述查询等公​​司。

1 个答案:

答案 0 :(得分:0)

选项:

首先find_by_sql()

描述:允许您在其上添加任何查询。

http://apidock.com/rails/ActiveRecord/Base/find_by_sql/class

第二次.where().joins()方法的组合。

但是要小心,如果在.joins()之后使用nil返回调用.where(),则会出现未定义方法的错误。这里的解决方案是首先测试.where()是否返回任何内容,然后您可以加入另一个表。

使用连接的可能方法:

joins(:tags)创建内部联接

joins('Left join foo...')允许您使用左外连接

joins(tagsForCompanies: :tags)如果您有N到N个关联,则嵌套连接。

请参阅API:

http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where

http://guides.rubyonrails.org/active_record_querying.html#joining-tables