Home > Enterprise >  Rails; How to select for a single database value with a scope
Rails; How to select for a single database value with a scope

Time:07-12

I have a database called students with columns like so enter image description here In my rails model with a scope or function, I would like to select for the single age value based on the id. The id column is unique. So something like

scope :get_age, -> (id) { where(id: id).select(:age) }

However this does not seem to work. I would like for the returned value to just be the int 12. Using something like pluck ends up returning an array which I would like to avoid. How would I go about selecting for just the value of 12?

CodePudding user response:

you know that for one id there is just one row (or no rows) so using where or pluck is not ideal, we want something it returns one row or nothing (find, find_by etc)

def self.get_age(id)
  find_by(id: id)&.age
end

some_id = 10
User.get_age(some_id) 

CodePudding user response:

Scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as where, joins and includes. All scope bodies should return an ActiveRecord::Relation or nil to allow for further methods (such as other scopes) to be called on it.

Reference: https://guides.rubyonrails.org/active_record_querying.html#scopes

That's why is not working as you expected.

I think the best alternative would be to do as Ursus suggested. Create a method, a query object, etc.

  • Related