我有一個非常複雜的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