Ruby 续集添加一个';范围';根据有条件的
代码如下所示:Ruby 续集添加一个';范围';根据有条件的,ruby,database,sequel,Ruby,Database,Sequel,代码如下所示: class Foo < Sequel::Model self.dataset_module do def property_active where('properties @> \'{"active": true}\'') end end end class Bar def foo_ids Foo.select(:other_model_id).distinct.all end def condition?
class Foo < Sequel::Model
self.dataset_module do
def property_active
where('properties @> \'{"active": true}\'')
end
end
end
class Bar
def foo_ids
Foo.select(:other_model_id).distinct.all
end
def condition?
...
end
end
它返回:
# when condition? is true
=> "SELECT DISTINCT \"other_model_id\" FROM \"foos\" WHERE (SELECT * FROM \"foos\" WHERE (properties @> '{\"active\": true}'))"
# when condition? is false
=> "SELECT DISTINCT \"other_model_id\" FROM \"foos\""
代码很好,但我不喜欢在WHERE
之后选择,有没有办法返回一个关于true
案例的好查询?比如:
"SELECT DISTINCT \"other_model_id\" FROM \"foos\" WHERE (properties @> '{\"active\": true}')"
我对Sequel处理链接和作用域的方式不太熟悉,但我会用ActiveRecord处理这个问题的方式来处理它。这行吗
class Bar
def foo_ids
scope = Foo.select(:other_model_id)
scope = scope.property_active if condition?
scope.distinct.all
end
end
这是可行的,希望有一个续集的方式来做到这一点。@zetacu不确定你在寻找什么不同。我使用的合成样式也用于。我在寻找是否有一种sequel方法将查询嵌套到其中,如Model.query.conditional\u query.query
类似Foo.where(bar:'something')。一些\u conditional\u resquel\u方法。where(Foo:'something')).all
通过这种方式,我可以将其添加到更具功能性的编程中,我相信这样做的唯一方法是添加一个作用域,但续集已经内置了该功能。@Zetau它真正属于你的应用程序,而不是委托给ORM。
class Bar
def foo_ids
scope = Foo.select(:other_model_id)
scope = scope.property_active if condition?
scope.distinct.all
end
end