Reputation: 2170
I am trying to use has_scope to filter all Keys that are not connected to a Room via my KeyRoomMapping Table.
I've created the scope in my Keys model, but I don't know how to call the scope in my view.
Models
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
Controller
class KeysController < ApplicationController
has_scope :without_rooms
def index
@keys = apply_scopes(Key).all
end
end
View
###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 %>
Upvotes: 1
Views: 734
Reputation: 52357
Add a boolean
option to has_scope
, which you'll use while building the path:
# controller
has_scope :without_rooms, type: :boolean
# view
link_to "Keys Without Rooms", '/keys?without_rooms=true' # or keys_path(without_rooms: true)
Upvotes: 1