简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM