views:

119

answers:

4

Hi there,

This might be a stupid questions but I wanted to know what happens if two users edit some data at once and then both click submit at the same time, I assumed Rails handled requests one after the other and so someone would get an error message but is this correct?

Thanks

Once one person has edited data I dont want it to be accessible or editable anymore, which is handled by validations

Ive got this validation in my model as well

def account_active
    if self.active == true
      return true
    else
      return false
    end
end

Where active is a Boolean set within the controller if the validations pass

A: 

As with all race conditions involving blind writes, last one wins unless you take steps to change that.

Joshua
+1  A: 

Your web server daemon would handle the requests one after the other; whichever request gets handled last becomes the newest update. Nobody would receive an error message unless you write some logic to handle such cases.

BipedalShark
+2  A: 

As has been mentioned in other answers, the latest write wins.

You might not think this is a problem but as there's no pessimistic lock preventing two users from having the same edit form open at once, both users may think the change they're making will be saved.

There is a way around this by using a version number or timestamp on your models that the system can use to tell "the user was editing version 1, but now there's version 2" and prevent the second user from overriding the first user's write.

Ryan Bates' awesome Railscasts series has covered the basics on how to set this up in Railscast 59: Optimistic Locking.

Jason Weathered
Thank you so much for the link, this is exactly what I was looking for. Once again Ryan Bates to my rescue
Karl Entwistle
A: 

Your original question was answered, but I'll add this:

For the validation, you can simply do the following

def account_active
  self.active?
end

Ruby implicitly returns the last line of the method.

Ryan Bigg
That's cool... not knowing that about Ruby, I'd write `return self.active`. Anything of the form `if <boolean> return <boolean> else return <other_boolean>` induces teeth-grinding.
Stephen P