2015-07-01 28 views
1

我有一類是生成查詢的數據庫:合併方法,以一個哈希,通過方法鏈接

他們應該串聯,所以我不重複我的代碼查詢(DRY)。

我想我可以做這樣的事情:

紅寶石

class Blah < ActiveRecord::Base 
    def no_scope 
    {scope: false} 
    end 

    def for_user(user_id) 
    {user_id: user_id} 
    end 
end 

現在我的查詢

Blah.no_scope.for_user(1) 

結果應是一個HASH

{user_id: 1, scope: false} 

回答

2

你嘗試實現這一目標?

class Blah < ActiveRecord::Base 
    scope :no_scope, -> { where(scope: false) } 
    scope :for_user, -> (id) { where(user_id: id) } 
end 

Blah.no_scope.for_user(1) # where(scope: false, user_id: 1) 
0

您只需要創建示波器。

class Blah < ActiveRecord::Base 
    scope :no_scope, -> {all} 
    scope :for_user, -> (user_id) {where(user_id: user_id)} 

end 


Blah.no_scope.for_user(1) # where(user_id: 1) 

參見scopes

0

爲了讓結果作爲一個真正的哈希,而不是一個ActiveRecord的關係,你做這樣的

class Blah < ActiveRecord::Base 
    scope :no_scope, ->{where(scope: false)} 
    scope :for_user, ->(id){where(user_id: id)} # no space in ->(id) 
end 

# give results as an array of hashes 
Blah.no_scope.for_user(1).map { |e| {scope: e.scope, user_id: e.user_id} } 

[{"scope"=>false, "user_id"=>1}]