如何在范围中使用连接?

时间:2013-06-26 17:32:45

标签: sql ruby-on-rails

我有一个使用多个过滤器的页面,除了一个过滤器外,一切正常。无效的过滤器需要检查哪个foos没有bars。也就是说,bar条记录不会与我希望显示的foo_id匹配foos

对于此示例,我们使用room foosno_bars进行过滤

我在范围(foo.rb)中有这样的东西:

  scope :not_validated, where("mark_validated = false")
  scope :not_located, where("grid_location_id IS NULL")
  scope :no_bars, joins("LEFT JOIN bars ON foos.id = bars.foo_id where").where("bars.id IS NULL")

  scope :room_1, where("room_id = 1")
  scope :room_2, where("room_id = 2")

我有一个过滤器parial:

<%= dropdown_tag filter_button_name("Room", "room") do %>
    <li><%= multi_filter_link "room", "room_1"%></li>
    <li><%= multi_filter_link "room", "room_2" %></li>
<% end %>

<%= dropdown_tag filter_button_name("Filter By", "filter") do %>
    <li><%= multi_filter_link "filter", "not_validated" %></li>
    <li><%= multi_filter_link "filter", "not_located" %></li>
    <li><%= multi_filter_link "filter", "no_bars" %></li>
<% end %>

当我尝试使用foos过滤器查看no_bars时,出现以下错误:

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE (bars.id IS NULL)' at line 1: SELECT `foos.*` FROM `foos` LEFT JOIN bars ON foos.id = bars.foo_id where WHERE (bars.id IS NULL)  

1 个答案:

答案 0 :(得分:1)

scope :no_bars, joins("LEFT JOIN bars ON foos.id = bars.foo_id where").where("bars.id IS NULL")

我想你想要:

scope :no_bars, joins("LEFT JOIN bars ON foos.id = bars.foo_id").where("bars.id IS NULL")