如何找到Rails不存在的关联?

时间:2011-11-25 23:04:36

标签: ruby-on-rails activerecord associations

我想使用关联在Rails / ActiveRecord中表示:

SELECT
  locations.* 
FROM
  locations
  LEFT JOIN items_locations ON locations.id = items_locations.location_id
  AND items_locations.item_id = 166
WHERE
  items_locations.item_id IS NULL

目前我有

class Item < ActiveRecord::Base
  has_and_belongs_to_many :locations
end

这将通过名为items_locations的简单映射表拉入与项目关联的所有位置。我的目标是更改此项以提取与项目无关的所有位置记录。

在我的模型中,协会应该怎样才能实现这一目标?

1 个答案:

答案 0 :(得分:0)

听起来你想要item_id不是166的所有位置。你没有指定你正在使用的Rails版本,但是在Rails 3中,如果item_id是一个变量,查询将如下所示:

Location.where("item_id != ?", my_item_id)

这将获得其item_id不等于my_item_id的所有位置。