【问题标题】:How can I call/use my scope in my view如何在我的视图中调用/使用我的范围
【发布时间】: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


【解决方案1】:

boolean 选项添加到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)

【讨论】:

  • 好吧,我想要 has_scope 以便我可以先显示所有键,然后允许用户单击该链接作为将其过滤到没有房间的键...
  • 有没有办法显示所有键启动,然后允许通过视图中的链接过滤 Key.without_rooms?
  • @SurgePedroza 我已经编辑了答案,尽管我认为这不是你能得到的最好的答案..
  • 这行得通,谢谢!如果您有任何其他建议,请随时分享。
  • @SurgePedroza 不客气!我只是没有仔细阅读第一次的问题,所以不要介意答案的第一部分:)
猜你喜欢
  • 2017-01-16
  • 2015-02-08
  • 2021-12-21
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
相关资源
最近更新 更多