Rails:在范围查询中使用服务类方法 [英] Rails: Using service class methods in a scope query
问题描述
我有一个用户模型.
我正在尝试将我的用户索引视图设置为仅显示那些已完成入职流程的用户.
I'm trying to set my user index view to show only those users who have completed an onboarding process.
我的做法是:
索引:
<% Users.onboarded.each do |user| %>
在我的 user.rb 中,我尝试为入职定义一个范围,如下所示:
In my user.rb, I tried to define a scope, for onboarding, as:
scope :onboarded, -> { where (:user_is_matchable?) }
我的组织服务类中有一个方法,它具有:
I have a method in my organisation service class which has:
class UserOrganisationMapperService
attr_accessor :user
private
def user_is_matchable?
profile.present? && matching_organisation.present?
end
当我尝试这个时,我收到一条错误消息:
When i try this, I get an error that says:
undefined method `onboarded' for Users:Module
谁能看到我哪里出错了?
Can anyone see where I've gone wrong?
推荐答案
首先:Users
或 User
在您的 user.rb
文件中.. 类的实际名称是什么?因为它应该是 User
而不是 Users
Firstly: Users
or User
in your user.rb
file.. what's the actual name of the class? because it should be User
not Users
其次:scope :onboarded, ->{ where (:user_is_matchable?) }
这是行不通的.作用域是一个 ActiveRecord 查询——它只能处理数据库中实际结构的细节.如果您的用户表中没有名为 user_is_matchable?
的列,那么此范围会报错并且不起作用.
Secondly: scope :onboarded, -> { where (:user_is_matchable?) }
this is just not going to work. a scope is an ActiveRecord query - it can only deal with details of the actual structure in the database. if you don't have a column in your users table called user_is_matchable?
then this scope will complain and not work.
您需要将该范围变成仅适用于数据库的范围.
you need to make that scope into something that would work just on the database.
我只是猜测(您没有在此处向我们提供您关系的完整结构)但您是否能够执行以下操作:
I'm only guessing (you haven't given us the full structure of your relations here) but would you be able to do something like:
scope :onboarded, -> { where ("profile_id IS NOT NULL AND matching_organisation_id IS NOT NULL") }
???
或者,您需要让它仅在 ruby 中运行 - 这会更慢(特别是如果您的表变得非常大,因为用户表不会这样做).但是如果你觉得它超级慢,那么你可以这样做:
Alternatively, you'll need to make it run just in ruby - which will be slower (especially if your table gets very big, as user-tables are wont to do). But if you're ok with it being super slow, then you could do this:
class User < ActiveRecord::Base
def self.onboarded
all.select(&:user_is_matchable?)
end
或类似的东西...
这篇关于Rails:在范围查询中使用服务类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!