I created a
Rails
belongs_to
User
belongs_to
class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.string :email, null: false
t.string :encrypted_password, null: false
t.string :description
t.string :avatar, null: false
t.integer :role_id, null: false
t.timestamps null: false
end
add_foreign_key :users, :roles
end
end
class CreateRoles < ActiveRecord::Migration[5.0]
def change
create_table :roles do |t|
t.string :name, null: false
t.text :description
t.timestamps null: false
end
end
end
class User < ApplicationRecord
before_create :set_default
belongs_to :role
private
def set_default
# self.role ||= Role.find_by(name: 'Client')
self.avatar = 'test'
end
end
class Role < ApplicationRecord
has_many :users
end
object
{
"email": "test@gmail.com",
"description": "testDesc",
"password": "12345678",
"password_confirmation": "12345678",
"role_id": 3
}
belongs_to
users
object
role
In Rails 5 a belongs_to
association is required to have the associated record present by default.
https://github.com/rails/rails/pull/18937
You can pass optional: true
to the belongs_to
association which would remove this validation check.
class User < ApplicationRecord
before_create :set_default
belongs_to :role, optional: true
...