Damir Nurgaliev Damir Nurgaliev - 27 days ago 7
Ruby Question

DRY in controller

i want to improve my code in controller according to DRY.

def create
blog.user = current_user
blog.save
respond_with blog, location: user_root_path
end

def update
blog.update(blog_params)
respond_with blog, location: user_root_path
end

def destroy
blog.destroy
respond_with blog, location: user_root_path
end


Every method has a respond_with blog, location: user_root_path. How can I hide it?

Answer

You can do a :after_action filter

After filters are run after the action completes. It can modify the response. Most of the time if something is done in an after filter, it can be done in the action itself, but if there is some logic to be run after running any of a set of actions, then an after filter is a good place to do it.

:after_action :responding, only: [:create, :update, :destroy]

def create
  blog.user = current_user
  blog.save
end

def update
  blog.update(blog_params)
end

def destroy
  blog.destroy
end

def :responding
  respond_with blog, location: user_root_path
end