Question

I'm currently developing a couple of modules to reuse code from my controllers on a Rails 3 using InheritedResources (last version) app.

My idea is to have some behavior that should be run after a successful create or update of the resource but, except from redeclaring the "create" or "update" actions, I'm not to sure on how to tackle this.

I'm currently using something like

module SessionStorable

  extend ActiveSupport::Concern
  include Base

  included do
    before_filter :setup_resource, :only => :new
    after_filter :reset_session_resource_id, :only => [:create, :update]
  end


  # ....

end

I have a particular resource setup I use which, among other things, adds the id of the resource to the session. After the resource has being successfully saved to the BD, I'd like to remove it's id from the session and that is what the after_filter does.

I've deal with it so far by also saving the updated_at info onto the session and comparing to see if the model was updated (if so, it should have been successfully) and run the method.

However, I'm not to happy with it (kinda hacky) and also I'm planning on having other modules that will work with resources also after they've been updated and wouldn't want to use the same approach twice.

Is there a hook on IR that I should be using? Or any other ideas on how to proceed?

Was it helpful?

Solution

I've solved it by using the "object.errors.empty?" condition. If there are no errors on the object after the create or update action, it should be safe to assume that the model was saved properly, and thus running the code would be fine.

OTHER TIPS

Maybe you could use an inheritance based approach instead:

class BaseController < InheritedResources::Base

before_filter :setup_resource, :only => :new
after_filter :reset_session_resource_id, :only => [:create, :update]

# ...
end

class YourController < BaseController
# ...
end

I'm sorry to use the answer feature for a comment, but since I can not do it under your answer I see no other option.

"object.errors.empty?" condition. If there are no errors on the object after the create or update action, it should be safe to assume that the model was saved properly

I think this is not always true, let me put you and example:

class Project < ActiveRecord:Base
  has_many :members
  # ...
end

Imagine you got a form for the project where you could also create members for it (nested forms). Errors in the creation of the associated members will make de project object invalid, but the project instance will return true for the method errors.empty?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top