Akash Pinnaka Akash Pinnaka - 6 months ago 60
Ruby Question

Forced validations for associated fields

I am using rails

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

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

Category model

class Category < ActiveRecord::Base
has_many :gigs

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.


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

belongs_to :user, optional: true