amronrails
amronrails

Reputation: 100

Rails avoiding duplication of database entry(many attributes)

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??

Upvotes: 0

Views: 39

Answers (1)

Tom Fast
Tom Fast

Reputation: 1158

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

Upvotes: 4

Related Questions