【发布时间】:2017-03-16 01:18:17
【问题描述】:
我正在尝试使用 has_scope 过滤所有未通过我的 KeyRoomMapping 表连接到房间的键。
我已经在我的 Keys 模型中创建了范围,但我不知道如何在我的视图中调用范围。
模型
class Key < ApplicationRecord
has_many :key_room_mappings, foreign_key: :key_id, dependent: :destroy
has_many :rooms, through: :key_room_mappings
###Is this the best way to find all Keys that are not connected to a room?
scope :without_rooms, -> { where.not(id: KeyRoomMapping.distinct.pluck(:key_id)) }
end
class KeyRoomMapping < ApplicationRecord
belongs_to :room
belongs_to :key
end
class Room < ApplicationRecord
has_many :key_room_mappings, foreign_key: :room_id, dependent: :destroy
has_many :keys, through: :key_room_mappings
end
控制器
class KeysController < ApplicationController
has_scope :without_rooms
def index
@keys = apply_scopes(Key).all
end
end
查看
###How can I use my scope to filter my list below, this is not working...
<%= link_to "Keys Without Rooms", {controller: 'keys', action: 'index', without_rooms: ''} %>
<% @keys.each do |key| %>
<tr>
<td><%= key.name %></td>
<td><%= key.copy %></td>
</tr>
<% end %>
【问题讨论】:
-
顺便说一句,
where.not(id: KeyRoomMapping.select(:key_id))将使用子查询 (where id not in (select key_id ...)),它应该比从数据库中提取所有不同的值然后使用单独的查询发送回更快。
标签: ruby-on-rails ruby scope has-many-through has-scope