带有has_scope的Rails 4:无声地失败

时间:2014-07-26 14:17:47

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

我有一个Rails 4.0.0应用程序,并希望包含has_scope gem。

非常简单直接的资源:

型号:

  class Thing < ActiveRecord::Base
  resourcify
  ...
  belongs_to :client
  validates_presence_of :name
  scope :by_client, ->  client  { where(:client => client)}
  scope :by_name, -> name { where(:name => name)}

控制器:

class ThingsController < ApplicationController
  include Pundit
  before_filter :authenticate_user!
  before_action :set_thing, only: [:show, :edit, :update, :destroy]
  after_action :verify_authorized, :except => [:index, :edit]
  has_scope :by_client, :type => :integer
  has_scope :by_name
 ....

 def index
   @things = apply_scopes(Thing).all
   puts current_scopes        
 end 

current_scopes始终为空哈希,无论应用何种范围,Thing.all都会传递给视图。范围本身就可以正常返回过滤后的记录 参数在那里:例如:

Started GET "/things?client=113" for 127.0.0.1 at 2014-07-26 16:07:32 +0200
Processing by ThingsController#index as HTML
  Parameters: {"client"=>"113"}

此设置有什么问题。我没有警告,没有方法丢失等等。只是完整的事情清单。我错过了一些配置选项吗?

知道了,在这种情况下,范围适用于表colums。这解决了它:

scope :by_client, ->  client  { where(:client_id => client)} 

而不是

has_scope :by_client

和参数

{"by_client"=>"113"}

就够了

1 个答案:

答案 0 :(得分:2)

基于我通过has_scope文档的简要阅读,您提供的参数是错误的,需要更改为

{ "by_client" => { "client" => "113" } }

您的控制器需要将has_scope更改为

has_scope :by_client, :using => :client, :type => :integer