Akash Pinnaka Akash Pinnaka - 1 year ago 100
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.

Answer Source

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

belongs_to :user, optional: true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download