0

(This is probably an easy question, but I didn't find the right words to google my problem)

In my controller I have a query like this:

information = Event.where(name: 'xyz')

Which works fine. In this case, only the model "event" gets queried and not other models like "Blog" or "Post". Instead of writing every query, I just want to call a method, which could look like this:

def find_information (model, word)
  information = model.where(name: 'word')
end

So, if I write find_information (Event, xyz), it should do:

information = Event.where(name: 'xyz')

or if I write find_information (Blog, xyz), it should do:

information = Blog.where(name: 'xyz')

I tried this:

model = Event

"#{model}".where(name: 'xyz')

But this throws an "undefined method `where' for "Event":String" error. How do I save the model in a variable? Thanks in advance

2 Answers 2

2

You are making a query to the name attribute with the string 'word'

  information = model.where(name: 'word')

You should query the argument with word.

def find_information (model, word)
  information = model.where(name: word)
end

This works for me.
Hope this help.

Sign up to request clarification or add additional context in comments.

Comments

1

If you are going to make user pass the model name, when making these kinds of queries, I suggest whitelisting them:

def find_information(klass_string, query)
  whitelisted_classes = %w(Event Blog Post)
  if whitelisted_classes.include?(klass_string)
    klass = klass_string.constantize
    result = klass.where(query)
  end
end

I know it is not fully what you asked for, so to answer your original question, if you pass a class as a variable then you can use it right away

klass = Event
klass.where(query)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.