Yurish
Yurish

Reputation: 1309

Rails: define column names to model

I have an existing database(Postgresql). How can i create models from it? How can i pass column names for Rails? As if something like this:

Person:

Name :table_name_for_name_attribute Surname :table_name_for_surname_attribute PersonalCode :table_name_for_perconal_code_attribute

Unfortunately, my database is not following Rails convention, because not all tables are named in English. Any ideas how can i map it?

UPDATE reverse_scaffold script generates only model, but i need controller and view forms also.

Upvotes: 1

Views: 2866

Answers (3)

EmFi
EmFi

Reputation: 23450

Rails doesn't need to know the column names it figures them out when it connects to the database.

As others have said you can specify a table name in the model.

As for generating controllers/views, you're pretty much own your own. script/generate scaffold is deprecated. It still works as far as creating things, but you need to pass all column names and times on the command line.

Instead have a look at the ActiveScaffold Plugin, it has a similar end result. But is much more robust and easier to adapt to model changes.

Upvotes: 0

user180844
user180844

Reputation:

In your model, you'll need to tell ActiveRecord what the table name and primary key field column is named if they don't follow the conventions.

class MyLegacyTable < ActiveRecord::Base
  self.table_name = "some_name"
  self.primary_key = "some_name_primary_key_field"
end

Once you've done that, ActiveRecord knows the some_name_primary_key_field as id, which makes life much easier.

Upvotes: 1

Damien MATHIEU
Damien MATHIEU

Reputation: 32629

You can define a table name not matching the model's using the table_name method.

class MyModel < ActiveRecord::Base
    def self.table_name
        'my_table_name'
    end
end

Change the value of 'my_table_name' to your effective table name.

For generating controllers and views with automatic methods to create, update, delete and view database objects, you should create a scaffold. There's some pretty good documentation on the rails guides about that.

Upvotes: 1

Related Questions