Nidhin S G
Nidhin S G

Reputation: 1695

Preventing Same Value from getting saved again onto DB Ruby on Rails

I have a table named user histories and a message will get saved on to that table along with the user ID. I also don't want same message to get saved again from the same user. Here is the part in my controller that saves the message.

    if delete == 1
      if UserHistory.where(comments:message, user_id:id).present?
        self.update_attributes(points: (self.points + point))
        UserHistory.where(comments:message, user_id:id).first.destroy        
      end
    elsif UserHistory.where(comments:message, user_id:id).present?
    else  
      self.update_attributes(points: (self.points + point))
      UserHistory.create(comments:message, user_id:id)        
    end

In this code if the message with same id is found i have given no action and else create a new field.

My Problem is its all working fine in my local machine. But when i deployed to development in my server its not working always.. Some times same messages from same user gets saved again. Why does this happen? Any solution?

Upvotes: 0

Views: 40

Answers (1)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

Do this in UserHistory model

validates_uniqueness_of :comments, :scope => :user_id

Update : In else block just reverse the lines so that validation fires before the points are updated

else      
  user_history = UserHistory.create(comments:message, user_id:id)
  self.update_attributes(points: (self.points + point)) unless user_history.blank?
end

Upvotes: 2

Related Questions