我有一个为db生成查询的类:
它们应该连接在一起,所以我不会重复查询代码(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}
答案 0 :(得分: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)
答案 1 :(得分:0)
答案 2 :(得分:0)
要将结果作为真正的Hash而不是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}]