Akash Pinnaka
Akash Pinnaka

Reputation: 475

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.

Upvotes: 0

Views: 39

Answers (1)

Argonus
Argonus

Reputation: 1035

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

belongs_to :user, optional: true

Upvotes: 2

Related Questions