用于LEFT JOIN查询的Rails SQL语法

时间:2015-05-20 16:51:17

标签: ruby-on-rails

我试图选择1)位于地图坐标内的所有通知,以及2)没有超级通知(因此在commentrelationships表中没有active_comment_relationship)。评论也属于课堂通知。 我无法正确使用SQL:

nelat = params[:NElatitude]
swlat = params[:SWlatitude]
nelng = params[:NElongitude]
swlng = params[:SWlongitude]
find_by_sql(" SELECT     *
              FROM       notices
              WHERE      latitude  < #{nelat}
              AND        latitude  > #{swlat}
              AND        longitude < #{nelng}
              AND        longitude > #{swlng}
              LEFT JOIN  commentrelationships
              ON         notices.id = commentrelationships.commenter_id
              WHERE      commentrelationships.commenter_id IS NULL
              LIMIT 50
           ; ")

notice.rb:

has_one :active_comment_relationship, class_name: "Commentrelationship",
                                      foreign_key: "commenter_id",
                                      dependent: :destroy
has_one :supernotice, through: :active_comment_relationship, source: :commentee

我已经尝试过这种方式,但它产生了一些非常奇怪的错误,我怀疑是因为它返回给定坐标的注释,而不是Notices:

find_by_sql(" SELECT     *
              FROM       notices
              LEFT JOIN  commentrelationships
              ON         notices.id = commentrelationships.commenter_id
              WHERE      commentrelationships.commenter_id IS NULL
              AND        latitude  < #{nelat}
              AND        latitude  > #{swlat}
              AND        longitude < #{nelng}
              AND        longitude > #{swlng}
              LIMIT 50
           ; ")

1 个答案:

答案 0 :(得分:0)

这是查询的粗略语法。您可以将这些放入命名范围,以便在需要时更清晰。它并不完全清楚您的模型是什么样的,所以如果这不起作用,请将它们添加到您的问题中以及您获得的确切错误消息。

Notices.joins("LEFT JOIN commentrelationships ON commentrelationships.commenter_id = notices.id")
  .where(commenter_id: nil)
  .where('latitude < ?', nelat)
  .where('latitude > ?', swlat)
  .where('latitude < ?', nelng)
  .where('latitude > ?', swlng)