Sequel根据条件加一个'scope'
Sequel add a 'scope' according to a conditional
代码如下:
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
我想修改 foo_ids
方法以根据 condition?
方法添加范围 property_active
。到目前为止,我想出了这个:
Foo.select(:other_model_id).where{ Foo.property_active if condition? }.distinct
它 returns:
# 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
之后添加 SELECT
的想法,有没有办法 return 对 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
代码如下:
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
我想修改 foo_ids
方法以根据 condition?
方法添加范围 property_active
。到目前为止,我想出了这个:
Foo.select(:other_model_id).where{ Foo.property_active if condition? }.distinct
它 returns:
# 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
之后添加 SELECT
的想法,有没有办法 return 对 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