Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

rails vs node db transactions

General • Asked by Sean M

Hi,

I am playing around with node.js and see promises everywhere even with db transactions. I was wondering why it is so different from rails.

For instance:

var db  = require('mongodb-promises').db('host:port', 'db_name'),
todoColl = db.collection('todos');

todoColl.insert({text: 'first task to do '})
  .then(function (result) {
    console.log('saved successfully');
  })
  .catch(function (err) {
    console.error('Error on insert ', err);
  });

in rails this would be something like

@todo = Todo.new(todo_params)
@todo.text = "first task to do"
if @todo.save
  render :json, @todo //I am not sure if format type matters in this example
else
  render json: @todo.errors, status: :unprocessable_entity
end

From my understanding (the following must be wrong somewhere, pls correct me):

Rails db transactions are synchronous and if @todo.save in controller is equivalent with after_save AR callback in the model, so rendering in controller fires after the validation is done and object is saved, BUT before it's committed to the database.

So basically we don't read the todo object from db after it gets there (since it's not committed yet), but we use @todo ivar which contains the knowledge to render html/json if data is valid and saved. Then if something goes wrong with the transaction then everything get's rolled back, so no problem. And we use after_commit instead of after_save in rails if we need some data that we wanna read back from db to make sure the data is already there (for instance elasticsearch indexing).

But my explanation must be wrong somewhere since if this is synchronous then we have to wait for the db transaction anyway, so we could use for instance if @todo.committed (this is just imaginary) or Todo.find(params(@todo.id)) instead of if @todo.save.

I. question:

Could you tell me where my explanation goes wrong?

II. As for node.js question:

Could you explain me why db transactions are handled asynchronously in node.js unlike in rails?


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.