ActiveRecord request for first object matching partial attribute
I have a scaffold for a model user
that has an attribute name
. The index looks like this:
I want to make a query that only finds the first record whose name starts with two letters: "Mr". So for the above, it will return an entry named "Mr Bar".
I know it might look something like this:
User.find_by(name: name[0].concat(name[1]) == "Mr") # doesn't work
+3
Neil
source
to share
1 answer
You can use the method where
to get users whose name starts with "Mr" and first to get the first query result
User.where("name like ?", "Mr%").first
+5
Ramkumar KR
source
to share