2017-07-26 41 views
0

我在我的PostgresDB中準備了一個名爲user_details的視圖。我創建了UserDetail實體和UserDetailRepository。在這裏你縮短了我的視圖版本,以可視化我的問題:使用參數化視圖與Hanami存儲庫

CREATE VIEW user_details AS 
SELECT id, user_name FROM users WHERE user_name like '$1#%' 

我的問題是如何使用Hanami存儲庫注入參數?

我可以在我的倉庫中使用原始數據庫,這裏描述的是http://hanamirb.org/guides/models/repositories/,但我更喜歡使用遷移在postgres中創建視圖。我不想改進查詢,但要知道是否可以使用Hanami進行用戶參數化查詢。感謝所有答案

回答

1

PostgreSQL不支持您描述的參數化視圖。它可以具有調用函數的視圖,以便訪問當前會話狀態,並且您可以在之前從該視圖中選擇數據,然後設置該狀態。不過,我建議你用一個參數來定義一個方法

class UserRepo 
    def user_details(prefix) 
    root.project { [id, user_name] }.where { user_name.ilike("#{ prefix }%") }.to_a 
    end 
end 

你得到的結果基本上是一樣的。如果您想使用user_details作爲基礎關係,則可以在回購中定義私有方法並從其他公共方法中調用該方法

class UserRepo 
    def user_details_filtered(user_name, min_user_id = 0) 
    user_details(prefix).where { id > min_user_id }.to_a 
    end 

    def user_details_created_after(user_name, after) 
    user_details(prefix).where { created_at > after }.to_a 
    end 

    private 

    # Don't call this method from the app code, this way 
    # you don't leak SQL-specific code into your domain 
    def user_details(prefix) 
    root.project { [id, user_name] }.where { user_name.ilike("#{ prefix }%") } 
    end 
end