使用Rails范围gem限制整数值的范围

问题描述 投票:0回答:1

我有一个模型CoffeeShops,其中包含一个整数值wifi_restrictions。

此字段的整数值将表示您可以使用wifi的小时数。

我正在尝试为此设置作用域,以便可以搜索

CoffeeShop.has_wifi_restrictions

...它将返回所有wifi_restrictions值大于0的咖啡店。

我正在使用rails has_scope gem:https://github.com/plataformatec/has_scope


我已经尝试过可以想到的所有变体来实现模型中的范围,但是此块的语法使我很头疼。

我也都尝试过]

has_scope :has_wifi_restrictions, type: :boolean

以及

has_scope :has_wifi_restrictions, type: :integer

我不确定这应该是什么。这里的一个附带问题是,在新的scope方法下,模型中的scope块是否实质上将整数值转换为布尔值。

my_coffee_shop.wifi_restrictions = 1

转换为

my_coffee_shop.has_wifi_restrictions = true

我不确定确切如何运作或如何正确实施。


我知道在我的模型中,我需要以下内容:

class CoffeeShop < ApplicationRecord
          scope :has_wifi_restrictions, ->(hours) { where(wifi_restrictions: hours.positive?) }
end

并且在控制器中,我需要类似的东西:

class CoffeeShopsController < ApplicationController
  has_scope :has_wifi_restrictions, type: :boolean
end

当我尝试进行搜索时

CoffeeShop.has_wifi_restrictions

我得到以下内容:

ArgumentError: wrong number of arguments (given 0, expected 1)

-

我很高兴在这里将所有问题捆绑在一起,但是我很感谢这两种解决方案,以及在理解如何使用范围方面的一般性建议。

我有一个模型Coffeeshops,其中包含一个整数值wifi_restrictions。此字段的整数值将表示您可以使用wifi的小时数。我正在尝试为...

ruby-on-rails ruby-on-rails-4 activerecord rubygems ruby-on-rails-5
1个回答
0
投票

您定义的has_wifi_restrictions范围要求您通过小时数。这似乎与您指定的目标不符(所有具有wifi限制的咖啡店)。后者将类似于

© www.soinside.com 2019 - 2024. All rights reserved.