Reputation: 16214
I have a class which is generating queries for a db:
They should concatenated, so I do not repeat my code for a query (DRY).
I thought I could do something like this:
ruby
class Blah < ActiveRecord::Base
def no_scope
{scope: false}
end
def for_user(user_id)
{user_id: user_id}
end
end
Now my query
Blah.no_scope.for_user(1)
RESULT SHOULD BE A HASH:
{user_id: 1, scope: false}
Upvotes: 1
Views: 89
Reputation: 42207
To give the result as a real Hash instead of a Activerecord relation, you do it like this
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} }
gives
[{"scope"=>false, "user_id"=>1}]
Upvotes: 0
Reputation: 2390
Did you try to achieve this?
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)
Upvotes: 2