WeezHard
WeezHard

Reputation: 2022

Rails 5 belongs_to scoped validation

lets say I have this model:

class Post < ApplicationRecord
  enum post_type: { post: 0, page: 1 }

  belongs_to :user
end

by default rails 5 will make the belongs_to :user association to be required. And If you pass optional: true will make this association to be optional. But what I want is the belongs_to :user association to be optional only when the post_type is page and when it is post to required.

How can I do it at the line belongs_to :user ?

At this moment I am doing this:

class Post < ApplicationRecord
  enum post_type: { post: 0, page: 1 }

   belongs_to :user, optional: true
   validates :user_id, presence: { scope: post? } 
end

But this will give me an error like:

NoMethodError: undefined method `post?' for #

Is this the correct way to do it? or there is another way?

Upvotes: 0

Views: 257

Answers (1)

Igor Drozdov
Igor Drozdov

Reputation: 15045

The user presence can be validated using if option:

validates :user, presence: true, if: :post?

Upvotes: 1

Related Questions