2016-11-02 4 views
1

私のKeyRoomMappingテーブルを介して部屋に接続されていないすべてのキーをフィルタするのにhas_scopeを使用しようとしています。ビューで自分のスコープを呼び出す/使用するには

私は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 %> 
+0

ところで、 'where.not(ID:KeyRoomMapping.select(:のkey_id))'サブクエリを使用します( 'どこIDではありませんで( select key_id ...) ')を実行する必要があります。これは、データベースからすべての個別の値を取り出して、別のクエリを使用して戻すよりも速くなければなりません。 –

答えて

1

がを追加パスを構築しているときに使用しますhas_scopeからオプション、:

# controller 
has_scope :without_rooms, type: :boolean 

# view 
link_to "Keys Without Rooms", '/keys?without_rooms=true' # or keys_path(without_rooms: true) 
+0

さて、私はすべてのキーを最初に表示できるように、has_scopeが好きで、ユーザーがキーを押して部屋を除外する方法としてリンクをクリックできるようにします... –

+0

すべてのキーを表示する方法はありますか? Key.without_roomsをビュー内のリンクを介してフィルタリングできるようにしますか? –

+0

@SurgePedroza私はあなたが得ることができる最高だとは思わないが、私は答えを編集しました。 –

関連する問題