我试图从缓存的数组中选择一个元素,但它不起作用。我正在做以下事情:
> t=Task.last
=> #<Task id: 26, title: "Soloff" created_at: "2017-12-11 13:48:17", updated_at: "2017-12-11 15:57:12">
> t.cached_reminds
=> [#<TaskRemind id: 3, deleted_state: false, task_id: 26, user_id: 1, date: "2017-12-27 23:00:00", created_at: "2017-12-11 16:28:34", updated_at: "2017-12-11 16:28:34">, #<TaskRemind id: 2, deleted_state: false, task_id: 26, user_id: 1, date: "2017-12-28 23:00:00", created_at: "2017-12-11 16:27:16", updated_at: "2017-12-11 16:27:16">]
所以我的请求呈现了好的数组,但是之后,当我尝试运行时:
t.cached_reminds.where(user_id: 1)
不被识别的 Action
你能帮我吗?
编辑:
形成我的模型任务:
def cached_reminds
Rails.cache.fetch([self, "task_reminds"]) {task_reminds.to_a}
end
奇怪的是,当我尝试运行时:
t.task_reminds.where(user_id: 1)
它的工作!!
最佳答案
您可以在 block 中返回缓存的 task_reminds
,无需将其转换为数组,这样它会为您提供一个 TaskRemind::ActiveRecord_Associations_CollectionProxy
对象,并且您能够使用 where
。与使用数组不同,您必须使用一些东西来过滤其中的元素:
def cached_reminds
Rails.cache.fetch([self, 'task_reminds']) { task_reminds }
end
last_task = Task.last.task_reminds
last_task.cached_reminds
# => => TaskRemind::ActiveRecord_Associations_CollectionProxy
last_task.cached_reminds.where user_id: 1
关于ruby-on-rails - 未定义方法 where for #<Array :0x007fd619b022b8>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757568/