ToddT
ToddT

Reputation: 3258

Ruby - convert string to model name for where search

I have an array of roles coming from params

roles = ["Guest", "Admin", "Member"]

These roles match my models.

I want to loop through these roles to search the matching models. Like so:

roles.each do |role|
  role.where(status: "active")
end

I've tried send and to_sym but my roles are not methods, but models. And role is not a symbol but a Model.

How can I accomplish this?

Upvotes: 0

Views: 106

Answers (1)

Ursus
Ursus

Reputation: 30071

This is how you could do this but it's just a part, we don't see where you store the result of your queries

roles.each do |role|
  role.constantize.where(status: "active")
end

And I also suggest you to check if these roles are only the ones you want to look for, sanitize the input

Upvotes: 1

Related Questions