Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails-返回方法返回true的所有记录_Ruby On Rails_Ruby - Fatal编程技术网

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之外使用过它们-请看一看-感谢您的回答。