1

I currently have two models

Location and Product

I have it configured that when a record is created in my production model, it creates a custom url based on the information it has gather from the location selected during the product creation

extend FriendlyId
friendly_id :slug_candidates, use: :slugged

def should_generate_new_friendly_id?
  name_changed? or location_id_changed?
end

def slug_candidates
 [
  [location.media_type, location.state, location.name, :name, :sku]
 ]
end

What I am currently testing is when a user decides NOT to fill out those very important fields, for it to throw an error message before creating

validates :name, presence: true
validates :sku, presence: true
validates :location_id, presence: true

What is happening in my case, is that it overlooks that validator and first tries to create the slug. If I remove the custom attributes to the url creation and list as

def slug_candidates
   [
    [:name, :sku]
   ]
end

it will work fine, running the field validators first. Assuming because those two are attributes on the given model directly.

Does anyone know why this is happening? I need for the validators to be picked up first since it contains all the relevant information for the url.

Charles
  • 50,943
  • 13
  • 104
  • 142
RubyNewbie
  • 547
  • 5
  • 21

1 Answers1

0

Solved

def slug_candidates
    if self.location_id.nil?
       self.errors.add(:location_id)
    else
       [
          [location.media_type, location.state, location.name, :name, :sku]
       ]
   end
end
RubyNewbie
  • 547
  • 5
  • 21