Ask A Question

Notifications

You’re not receiving notifications from this thread.

rails vs node db transactions

Sean M asked in General

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?

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.