Ruby中的活动记录查询接口

时间:2017-11-03 14:17:55

标签: mysql sql ruby-on-rails ruby

有人可以协助我如何编写这个自定义查询和Active Record查询界面,我仍然是Ruby的新手,我读到Active记录界面查询适用于大多数数据库,因此推荐使用。提前谢谢

sql = "select count(distinct(email)) as rcount from resources r
           inner join capabilities c
           on c.resource_id = r.id
           inner join skills s
           on c.skill_id = s.id "
sql += " where " unless (params[:country_id].to_i.zero? && params[:skill_id].to_i.zero?)

sql += "r.nationality = '" + Country.get_country_name(params[:country_id]) + "'" unless (params[:country_id].to_i.zero?)

sql += " and " unless (params[:country_id].to_i.zero? || params[:skill_id].to_i.zero?)

sql += "s.id =" + params[:skill_id] unless (params[:skill_id].to_i.zero?)

2 个答案:

答案 0 :(得分:1)

假设您的模型关系设置正确。这是你的SQL的ActiveRecord翻译。

Resource.select(:email).joins(capabilities: :skills).distinct.count

答案 1 :(得分:0)

您可以直接在模型上使用ActiveRecord::Querying#find_by_sql

示例:

Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"