2

I have a string containing a set of ActiveRecord models and I would like to do the same query for every model passed as string.

model_type = 'Comment'
id = 1
record = model_type.find(id)

model_type = 'Post'
id = 1
record = model_type.find(id)

How can I do that?

2 Answers 2

4

You need to use the constantize method.

model_type.constantize.find(id)

Do be careful when accepting arbitrary user data and evaluating it like this. You may generate exceptions for unknown classes.

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

Comments

1

constantize nice, I hadn't seen that one before. Here's how I've done it in the past:

@list = Kernel.const_get(@type).find_by_id_and_account_id(params[:id], current_account.id)

I'm not sure which is better, constantize looks cleaner :)

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.