我有一个非常复杂的SQL查询,我想转换为RoR的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
我需要在公司控制器搜索功能针对上述查询的公司。
是的,我能做到这一点,但我宁愿使用回报率的ORM ... – user3807877 2014-10-27 15:48:21
事情是这样的代码? ([:city =“?”AND country =“?”,“NY”,“US”])。joins(:tags).where(t.Name REGEXP'?','/ regexp /' ) 看看其中()方法,并加入()方法: http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where HTTP://api.rubyonrails .org/classes/ActiveRecord/QueryMethods.html#method-i-joins – 2014-10-27 15:58:37
此外,你应该使用rails规范中的pluralize:has_and_belongs_to_many:公司 – 2014-10-27 16:04:26