Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing Model with String input

Lets say I wish to make a page that can query the desired object with type(string) and id(int).

/query?type=people&id=1

would fetch me

Person.find(1)

whereas

/query?type=cities&id=123

would fetch me

City.find(123)

However, I have problems as to how to translate strings into the desired model class.

The only way I can think of is

case params[:type]
 when 'people'
  @object = Person.find(params[:id])
 when 'cities'
  @object = City.find(params[:id])
end

However, this method will be quite problematic if I have more types of models.

Is there a better way?

Thank you in advance,

like image 269
rickypai Avatar asked Feb 27 '12 09:02

rickypai


People also ask

What is a model reference?

Like libraries, model references allow you to define a set of blocks once and use it repeatedly. Model references provide several advantages that are unavailable with subsystems and libraries.

What are the inputs and outputs of a model?

tf.keras.Model() Model groups layers into an object with training and inference features. Arguments. inputs: The input (s) of the model: a keras.Input object or list of keras.Input objects. outputs: The output (s) of the model. See Functional API example below. name: String, the name of the model. There are two ways to instantiate a Model:

How do I simulate a referenced model?

You can simulate a referenced model either interpretively (in normal mode) or by compiling the referenced model to code and executing the code (in accelerator mode). For details, see Choose Simulation Modes for Model Hierarchies.

How do you reference a model in a block?

Model References. You can include one model in another by using a Model block. Each instance of a Model block is a model reference. For simulation and code generation, blocks within a referenced model execute together as a unit. The model that contains a referenced model is a parent model.


1 Answers

Try:

klass = params[:type]
klass.singularize.classify.constantize.find(params[:id])

Edit:

@object = params[:type].singularize.classify.constantize.find(params[:id])
like image 169
Syed Aslam Avatar answered Oct 22 '22 21:10

Syed Aslam