Can I add a column to the ActiveRecord model, which is a foreign key?

I can easily create a sketch or model in Rails with a field that is a link (foreign key) to another model:

rails g model Cat owner:references rails g scaffold Cat owner:references 

But I can not do the same for adding a column to the hyphen:

 rails g migration AddOwnerToCats owner:references 

The above example creates a migration file as follows:

 class AddOwnerToCats < ActiveRecord::Migration def change add_column :cats, :owner, :references end end 

And when I try to run it using rake db:migrate , I get the following:

 SQLite3::SQLException: near "references": syntax error: ALTER TABLE "cats" ADD "owner" references 

So, is there a way to add a column that is a link to another model? Or I just need to do:

 rails g migration AddOwnerToCats owner_id:integer 

And then go to the move and add an index for owner_id ?

+4
source share
2 answers

One way I can think of and a workaround is to simply create a column and give a join condition in the model. i.e.

 has_many :x, :class_name => y, :foreign_key => z 
0
source

I know this is an old question, but with Rails 5 (and possibly earlier versions) the official docs are updated

0
source

Source: https://habr.com/ru/post/1498918/


All Articles