2017-03-02 36 views
0

的代碼是這樣的:續集一個「範圍」根據添加給條件

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 

,並返回:

# 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\"" 

的代碼是好的,但我不喜歡的想法,SELECTWHERE後,有沒有返回true大小寫的好查詢的方式?是這樣的:

"SELECT DISTINCT \"other_model_id\" FROM \"foos\" WHERE (properties @> '{\"active\": true}')" 

回答

1

我不是太熟悉的方式處理續集鏈接和範圍,但這是我如何與ActiveRecord的處理這種方式接近它。這是否工作?

class Bar 
    def foo_ids 
    scope = Foo.select(:other_model_id) 
    scope = scope.property_active if condition? 
    scope.distinct.all 
    end 
end 
+0

這個工程,希望有一個續集的方式來做到這一點。 – zetacu

+0

@zetacu不知道你在找什麼,這是不同的。我用過的構圖風格也用於[Sequel入門](https://github.com/jeremyevans/sequel#an-introduction)。 – coreyward

+0

我正在查看是否有一種將查詢嵌套到一箇中的續集方法,比如'Foo.where(bar:'somethig')''Model.query.conditional_query.query'。some_conditional_restriction_sequel_method.where(foo:'something ').all'這樣我就可以將它添加到更多功能的編程中,我相信唯一能做到這樣的事情的方法是添加一個範圍,但跳過已經有內置的續集。 – zetacu