簡體   English   中英

Ruby on Rails:期望使用ActiveRecord :: Relation對象,但要獲取Model本身

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

無法理解為什么我得到模型對象而不是關系對象。 模型Activity ,控制器索引操作:

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

:my是有效范圍, filtering_params是一個哈希,其鍵的名稱與模型中的作用域相同。 在模塊中定義的方法filter

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

如果filtering_params不是空哈希,則一切正常, @activities是Relation對象。 但是,如果錯誤地將空哈希作為參數傳遞給filter方法,我將在視圖“ #Class ...的未定義方法”中出現錯誤。 我在控制台中嘗試了一下,發現在這種情況下@activities.object_idActivity.object_id相同。 但是請說明預期的關系對象如何本身成為模型類?

控制器中的filtering_params方法:

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

模型:

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

這很難弄清楚,但是我猜想當您分配results = self ,您是在課程級別進行的。 例如,如果將其更改為results = self.where(nil)results = self.where(nil)指向一個集合。

或者,您可以添加以下子句:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM