-
Notifications
You must be signed in to change notification settings - Fork 19
ActsToToggle
Nícolas Lazarte edited this page Feb 4, 2014
·
1 revision
ActsToToggle is a controller concern created to provide the action toggle
in the controller.
Include concern in controller
class PagesController < ApplicationController
include ActsToToggle
...
end
create route
resources :pages do
member do
put :toggle
end
end
use
<%= link_to "Toggle publish", toggle_user_path(@user, field: 'publish'), method: :put %>
Attribute to toggle
By default, the attribute specified in the parameter is considered as boolean, then it just made a toggle! this attribute. This action is one method in the concern, them if you want customize just overwrite method in controller.
Original
def toggle_attribute!
return false if resource.blank? && params[:field].blank?
resource.toggle!(params[:field])
end
Customized example (write in controller included concern)
private
def toggle_attribute!
return false if resource.blank? && params[:field].blank?
if params[:field] = 'status'
resource.update_attributes(status: (resource.status == 'active' ? 'inactive' : 'active'))
else
resource.toggle!(params[:field])
end
end
Redirect path after toggle action
Method that defines the path to be redirected after performing the toggle
action. By default the path is :back
, if you want customize just overwrite this method.
Original
def after_toggle_path
request.env["HTTP_REFERER"]
end
Customized example (write in controller included concern)
private
def after_toggle_path
root_path
end