AndrewShmig
AndrewShmig

Reputation: 4923

Metaprogramming in Ruby On Rails

I have an array of strings: ["users", "torrents", "comments"] these strings are the names of my bd tables.

how can I in .each loop connect to these tables and select|insert some data?

Upvotes: 0

Views: 112

Answers (1)

Matthew Rudy
Matthew Rudy

Reputation: 16844

Avoid using eval

here is a simple solution using constantize

note: constantize will not allow arbitrary code to evaluated, it will just try to fetch a ruby constant, namely a Class

["users", "torrents", "comments"].each do |table_name|
  # "users" => "User"
  #   or more complex
  # "some_models" => "SomeModel"
  #
  class_name = table_name.singularize.camelize

  # "User" => User
  model_class = class_name.constantize

  # do something with it
  model_class.create!(:value => 12345)
end

Upvotes: 6

Related Questions