If I have command and model like this:
Command
$ bin/rails generate model User name:string firstname:string
$ bin/rails genarate model Profile username:string password:string
model generated by rails
class User < ApplicationRecord
has_one :profile
end
Class Profile < ApplicationRecord
belongs_to :user
end
Is the 1:1 association in migrate folder generated automatically by rails or I have to implement it myself?
CodePudding user response:
The migration file for Profiles (class CreateProfiles < ActiveRecord::Migration
) should have a foreign key declaration like this:
t.references :user, null: false, foreign_key: true
whole code:
create_table :profiles do |t|
t.string :username
t.string :password
t.references :user, null: false, foreign_key: true
t.timestamps
end
That can also be generated automaticaly with the generator command by adding user:references
like so:
$ bin/rails genarate model Profile username:string password:string user:references
You can also refer to the Active Record Migrations guide and search for "references" on that page.
CodePudding user response:
ActiveRecord::Associations::ClassMethods does not create database columns automatically. That would actually be a very risky and undesirable feature. You do not want your Rails server to change the DB schema at runtime. Thats what migrations are for.
You can however use the references
"type" in the generators (also aliased as belongs_to
) which creates a a foreign key column as well as an assocation in the model:
bin/rails g model Profile username:string password:string user:references
class CreateProfiles < ActiveRecord::Migration[7.0]
def change
create_table :profiles do |t|
t.string :username
t.string :password
t.references :user, null: false, foreign_key: true
t.timestamps
end
end
end
class Profile < ApplicationRecord
belongs_to :user
end
There is no equivilent for adding has_one
or has_many
assocations from generators as they don't actually correspond to a database column on this model.
If you need to add a foreign key column to the table after the fact you do it by generating a migration:
bin/rails g migration AddUserIdToProfiles user:refereces