developer033 developer033 - 3 months ago 71
Ruby Question

Rails 5 belongs_to association must exist

I created a

Rails
API project and for some reason I'm facing an issue with
belongs_to
associtation in Rails 5.

The problem is that I can't save the object
User
if I set
belongs_to
in Model.

Schema:

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


Models:

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


I'm trying to save a simple
object
like this:

{
"email": "test@gmail.com",
"description": "testDesc",
"password": "12345678",
"password_confirmation": "12345678",
"role_id": 3
}


However I can't because I always receive the following error:

enter image description here

Note: If I remove the
belongs_to
of
users
it works, however if I do it I can't access the
object
role
in another actions.

Answer

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
  ...