masa_ekohe
masa_ekohe

Reputation: 79

How to apply a custom validation to association in ActiveRecord

I have Item model and Theme model like so:

class Item
  belongs_to :mobile_theme, class_name: 'Theme'
end

class Theme
  has_many :items

  enum theme_type: { desktop: 0, mobile: 1 }
end

I want to validate that item.mobile_theme.theme_type == :mobile when an association is created. ( I want to prevent Theme with theme_type = :desktop to get associated with Item as a mobile_theme)

How could I do that?

Upvotes: 0

Views: 454

Answers (1)

arieljuod
arieljuod

Reputation: 15838

You can add custom validators or custom validation methods https://guides.rubyonrails.org/active_record_validations.html#custom-methods

class Item
  validate :reject_non_mobile_theme

  private

  def reject_non_mobile_theme
    errors.add(:mobile_theme, 'Theme must be mobile') unless mobile_theme.mobile?
  end

Upvotes: 2

Related Questions