![](/img/trans.png)
[英]Rails4: Get an ActiveRecord::Relation from a model or an already chained relation
[英]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_id
與Activity.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.