简体   繁体   中英

Ruby on rails: expect ActiveRecord::Relation object but get Model itself

Can't understand why I am getting Model object instead of Relation object. Model Activity , controller index action:

clacc ActivitiesController < ApplicationController
def index
  @activities = Activity.my(current_user).filter(filtering_params)
end

:my is valid scope, filtering_params is a hash with key's names same as scopes in the model. Method filter defined in module:

module Filterable
  extend ActiveRecord::Concern

  def filter(filtering_params)
    results = self
    filtering_params.each do |key, value|
      results = results.public_send(key, value)
    end
    results
  end
end

If filtering_params is not empty hash, everything works fine and @activities is Relation object. But if it happend by mistake empty hash passed as argument to filter method, I am starting get an error in the view "undefined method each for #Class...". I try it in console and find what in this case @activities.object_id is the same as Activity.object_id . But please explain how expected relation object becames a model class itself?

filtering_params method in controller:

private

def filtering params
  params.merge!(completed: "false") unless params[:comleted]
  params.merge!(select_all: "true") unless params[:select_all]
  params.slice(:completed, :select_all)
end

Model:

class Activity < ActiveRecord::Base
include Filterable
...
scope :my, -> (user) { # scope here }
scope :completed, # other scope
scope :select_all, # other scope

This is hard to figure out but I guess that when you are assigning results = self , you are doing it at class level. If you change this to, in example, results = self.where(nil) , you'll be pointing to a collection.

Alternatively you can add the clause:

results = results.public_send(key, value) if value.present?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM