0

Is there any way to make the model execute an error message like flash[:notice]??

I want to avoid entering the same data to my database twice..

before_save :no_duplication

private

    def no_duplication
        if CarPrice.where(:car_id => self.car_id).where(:agent_id => self.agent_id).blank?
            return true
        else
            return false
        end
    end

This code stop duplicating but it doesn't send any error messages. How can I fix that??

amronrails
  • 100
  • 13
  • Possible duplicate of [Accessing rails flash\[:notice\] in a model](http://stackoverflow.com/questions/2701932/accessing-rails-flashnotice-in-a-model) – Pavan Oct 20 '15 at 15:36

1 Answers1

4

I would prefer using a model validation:

validates :car_id, uniqueness: { scope: :agent_id }

Take a look at the docs for other options such as allow_nil: true, etc. http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

I would also recommend adding a unique index:

add_index :name_of_table, [:car_id, :agent_id], unique: true
Tom Fast
  • 1,138
  • 9
  • 15