Rails 4 with has_scope: fails silently

给你一囗甜甜゛ 提交于 2019-12-08 04:16:22

问题


I have a Rails 4.0.0 app and want to include the has_scope gem.

Very simple and straight resources:

Model:

  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)}

Controller:

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 is always an empty hash and Thing.all is passed to the view, no matter what scope is applied. The scopes themself are ok and properly return the filtered records Parameters are there: eg:

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"}

What is wrong with this setup. I got no warnings, no method missing etc. Just the full list of things. Did i miss some configuration option or anything?

Got it, in this case, scope works on table colums. This fixes it:

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

and than a

has_scope :by_client

and parameters

{"by_client"=>"113"}

are enough


回答1:


Based on the brief read I've had through the has_scope documentation, the parameters has you're supplying is wrong and needs to be changed to

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

And your controller needs to change the has_scope to

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


来源:https://stackoverflow.com/questions/24971950/rails-4-with-has-scope-fails-silently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!