如何在Rails Active Record中实现AND子句?

时间:2015-03-03 02:58:02

标签: ruby-on-rails ruby-on-rails-4 activerecord

我有以下查询:

select source_names.id as source_id, source_names.name as source_name, source_types.id as source_type_id,source_types.name type_name,event_sources.id
  from source_names
    left join source_types
    on source_type_id = source_types.id
   left join event_sources
   on source_names.id = event_sources.source_id and event_id = 1


result = SourceName.joins('
                                LEFT JOIN source_types ON source_type_id = source_types.id
                                LEFT JOIN event_sources ON source_names.id = event_sources.source_id
                              ').where('event_id =?',event_id).select('source_names.id as source_id, source_names.name as source_name, source_types.id as source_type_id,source_types.name type_name,event_sources.id').all

的产率:

select source_names.id as source_id, source_names.name as source_name, source_types.id as source_type_id,source_types.name type_name,event_sources.id
      from source_names
        left join source_types
        on source_type_id = source_types.id
       left join event_sources
       on source_names.id = event_sources.source_id WHERE event_id = 1

但我想要and event_id = 1

我是怎么做到的?

1 个答案:

答案 0 :(得分:1)

如果您不想要WHERE,请不要使用.where

只需将其添加到您的联接中:

SourceName.joins('
  LEFT JOIN source_types ON source_type_id = source_types.id
  LEFT JOIN event_sources ON source_names.id = event_sources.source_id and event_sources.event_id = 1')