Akash Pinnaka Akash Pinnaka - 11 days ago 10
Ruby Question

Forced validations for associated fields

I am using rails 5.0.0.1

When I submit a form, validations for associated fields are coming into action.

I have Gig, User, Category and other models

I am using devise for user authentication

Gig model

class Gig < ActiveRecord::Base
has_many :proposals
belongs_to :category
has_many :abilities
has_many :skills, through: :abilities
belongs_to :user
end


User model

class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

has_many :gigs
has_many :proposals
end


Category model

class Category < ActiveRecord::Base
has_many :gigs
end


When I try to create the gig in console, the transaction rolls back.

the error messages are


["Category must exist", "User must exist"]


I appreciate your help. Thanks in advance.

Answer

In rails 5 when you add belongs_to it makes this field required. Try this

belongs_to :user, optional: true