将sql查询转换为Activerecord查询rails 4

时间:2015-07-20 13:11:09

标签: mysql ruby-on-rails activerecord

我有这个SQL查询:

      sub = "(select Name from other_holders s where s.share_holder_id=share_holders.id and s.other_holder_type_id=1) as secondHolderName"   
      sub1 = "(select Name from other_holders s where s.share_holder_id=share_holders.id and s.other_holder_type_id=2) as thirdHolderName"       
      @shareHolders=ShareHolder.select("Folio_no,Name,#{sub},#{sub1}")           

我从这个查询得到了所需的结果,但我对此不满意。我想将整个查询转换为Activerecord查询。请帮帮我。

1 个答案:

答案 0 :(得分:0)

class ShareHolder < ActiveRecord::Base
  has_many :second_holders, class_name: OtherHolder, ->{where( older_holder_type_id: 1)}
  has_many :third_holders, class_name: OtherHolder, ->{where(other_holder_type: 2)}
end