【问题标题】:Rails has_scope with if conditionRails has_scope 与 if 条件
【发布时间】:2014-03-29 07:20:22
【问题描述】:

在我的表单中,我有很多字段,当我在我的 url 中提交表单时,我看到很多空参数,例如 url?a=&b=&c= 并且我的 has_scope 模型认为我想使用这个参数,但值为空,但这是错误的。

我的模型和控制器的一部分:

class CarsController < ApplicationController
 has_scope :by_manufacturer
 has_scope :by_price, :using => [:price_from, :price_to]
end

class Car < ActiveRecord::Base
 scope :by_manufacturer, -> vehicle_manufacturer_id { where(:vehicle_manufacturer_id => vehicle_manufacturer_id) }
 scope :by_price, -> price_from, price_to { where("price >= ? AND price <= ?", price_from, price_to) }
end

我怎么能写出这样的东西:

if vehicle_manufacturer_id.present? 
 has_scope :by_manufacturer
end

如何检查现场存在是正确的?在哪里写,怎么写?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 has-scope


    【解决方案1】:

    Has_scope 有一个 :if 条件,您可以使用它来确定何时应该使用范围。示例:

    has_scope :by_manufacturer, if: vehicle_manufacturer_id.present?
    

    或者给作用域本身添加一个条件:

    scope :by_manufacturer, -> vehicle_manufacturer_id { where(:vehicle_manufacturer_id => vehicle_manufacturer_id) if vehicle_manufacturer_id.present? }
    

    我现在无法对其进行测试,但这应该可以。但是,我认为您的问题不在于您是否称范围。 URL 参数从您的视图传递到您的控制器。范围仅确定在特定条件下返回哪些记录,它们没有说明应该显示哪些 URL 参数。

    【讨论】:

    • 如何将紧凑型与 has_scope 一起使用:
    • 抱歉引起了我的注意...但是如何将紧凑型与 has_scope 一起使用?
    • 好的,似乎可以工作...只是如何:scope :by_price, -&gt; price_from, price_to { where("price &gt;= ? AND price &lt;= ?", price_from, price_to) if (!price_from.nil? &amp;&amp; !price_to.nil?)} 是否只输入来自或只输入价格?也许每个都有一个has_scope:从价格还是到价格?
    • 有什么问题?您使用 &&,因此如果 price_from 或 price_to 不存在,则不会调用范围。
    • 可能是这样的情况:用户在数据库中仅输入 price_from 或仅 price_to 我必须搜索!只是在其他条件下
    猜你喜欢
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多