Reputation: 13
I'm new to Rails & ActiveRecord and am working on my first CLI app. I want to allow a user to be able to retrieve information based on their target input. For example, if they want a list of happy people, they should get a list of ALL happy people.
I have come up with this code, it works but not really.
types_list = People.where(types: input).map {|ppl| ppl.person_name}
Some of the information is is stored like this:
id | person_name | types
----------------------------------
01 | James Lee | happy
02 | Sandra Lee | sad
03 | Daniel Seong | happy, sad
04 | Cody Kim | happy
05 | etc... |
The above code only returns "James Lee, Cody Kim". However, I also want it to include "Daniel Seong". Basically all person_name:
where the types:
includes happy.
Upvotes: 0
Views: 75
Reputation: 2727
@rajdeep-singh is totally right!
Additionally you could add a scope to the Person model:
# app/models/person.rb
scope :happy, -> { where("types LIKE ?", "%happy%") }
Usage:
Person.happy.pluck(:person_name)
Upvotes: 0
Reputation: 17834
You need to match the string instead, if types
is a string
or text
field, try this
types_list = People.where("types LIKE ?", "%#{input}%").map {|ppl| ppl.person_name}
It will return every record with types
hello
.
Hope that helps!
Upvotes: 2