开发者

Ror creating table association

开发者 https://www.devze.com 2023-03-17 11:55 出处:网络
I have created a table and now I want to add an association (has_many relationship) to the table. How can I do it 开发者_Go百科if I have already created a table and rake db:migrate has been done after

I have created a table and now I want to add an association (has_many relationship) to the table. How can I do it 开发者_Go百科if I have already created a table and rake db:migrate has been done after creation of model?

Is it possible to add association (has_many relation) in a table after it's creation in ror?


You can use migrations to add the column that connects the two tables. Take care on the naming conventions.


If MyModel has_many :foos, then there's actually no column relating to that relation in the my_models table. Instead, you will need to create the Foo model with a my_model_id column, or generate a migration to add that column to the existing foos table.

That is, you want to run either:

rails generate model Foo <other fields> my_model_id:integer

or

rails generate migration add_my_model_id_to_foo my_model_id:integer

Note that the syntax about is for Rails 3; under Rails 2, you need ruby script\generate ...


Yes. In your terminal, do the following:

rails generate migration AddColumnToTableName column_id:integer

Replace TableName with the name of the table you need to add the column to and column with the name of the model that gets the belong_to association.

0

精彩评论

暂无评论...
验证码 换一张
取 消