0

I have this problem. I need to use an existing table on a mysql database. The name of the table is not compatible with RoR conventions and I need to remap the table name and the name of the attributes. I have created a scaffold to visualize on a web page the content of the table but I can't change the mapping. Is there a solution to indicate to RoR the relation between the name of the class and the name of the table in the database? and a solution to indicate the relation between the attribute of the class and field on the table? Thanks.

2 Answers 2

1

The table name can be specified using table_name class method.

For the attributes/column, you need to explicitly specify aliases for the attributes using alias_attribute method. For example, if you have name_of_thing column, but want to treat it as name, then you need something like this in your model:

class CreateUtenti < ActiveRecord::Base
  self.table_name = "another_name"
  alias_attribute :name, :name_of_thing
end
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks to you too. In this case rake db:migrate give me this error: rake aborted! NoMethodError: undefined method `table_name=' for CreateUtenti:Class
@GiovanniDiClemente does your CreateUtenti class inherits from ActiveRecord::Base?
what Rails version do you use?
0

Yes you can pass table name in model like:

class YourModel < ActiveRecord::Base
  self.table_name = "pass_table_name_here"
end

2 Comments

Thank for your answer. I have tried but rake db:migrate give me an error: rake aborted! ArgumentError: wrong number of arguments (given 2, expected 0..1)
Caused by: ArgumentError: wrong number of arguments (given 2, expected 0..1) Tasks: TOP => db:migrate (See full trace by running task with --trace) Macintosh:telwebtt giovannidiclemente$ rake db:migrate --trace ** Invoke db:migrate (first_time) ** Invoke db:load_config (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:load_config ** Execute db:migrate rake aborted! ArgumentError: wrong number of arguments (given 2, expected 0..1)

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.