Ruby on rails Rails-返回方法返回true的所有记录
我有一个方法:Ruby on rails Rails-返回方法返回true的所有记录,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个方法: class Role def currently_active klass = roleable_type.constantize actor = Person.find(role_actor_id) parent = klass.find(roleable_id) return true if parent.current_membership? actor.current_membership? end end Role.wh
class Role
def currently_active
klass = roleable_type.constantize
actor = Person.find(role_actor_id)
parent = klass.find(roleable_id)
return true if parent.current_membership?
actor.current_membership?
end
end
Role.where(currently_active: true)
我想返回此方法为真的角色的所有实例,但是不能使用all.each遍历它们,因为这大约需要20秒。我尝试使用where语句,但是它们依赖于模型的属性而不是方法:
class Role
def currently_active
klass = roleable_type.constantize
actor = Person.find(role_actor_id)
parent = klass.find(roleable_id)
return true if parent.current_membership?
actor.current_membership?
end
end
Role.where(currently_active: true)
这显然会引发一个错误,因为没有名为Current_active的属性。如何以最有效的方式执行此查询,如果可能,如何使用活动记录而不是数组
提前感谢这似乎是不可能的,在您的情况下,您必须进行迭代。我认为最好的解决方案是在表中添加一个
Boolean
列,这样您就可以按查询进行筛选,这样会更快
在编辑后看到您的方法后,似乎它不会因为循环而变慢,而是因为Person.find
和klass.find
而变慢,您正在这里进行大量查询和数据库读取。(您最好使用关联并进行某种紧急加载,这样会更快)
另一个解决方法是可以使用ActiveModelSerializers
,在序列化程序中,可以根据条件获取对象的属性。然后,您可以使用逻辑忽略具有某种标志或属性的对象
尝试选择方法:
这取决于要使用ActiveRecord,您应该对数据库列进行操作的
复杂的\u块。显示您的复杂的\u块
我已经添加了块…有没有任何方法可以在数据库列以外的其他内容上使用活动记录关系…?我从未在JSON之外使用过它们-请看一看-感谢您的回答。