Today I would like to show you how you may setup an action_link with the following features:
- actionlink may be hidden for a record
- showing success/error messages and updated record in response
We will use the example from my howto as a base.
Our task is to show a ‘fire’ action_link for players which are older than 6 years.
Note: We may have used existing authorization methods to accomplish this, however this is nt a question about authorization it s a simple logical decision.
1. Let s start by adding a ‘fire’ action_link to active scaffold’s config block of players controller:
active_scaffold :player do |conf| conf.action_links.add 'fire', :confirm => 'are_you_sure', :type => :member, :method => :put, :position => false end
2. Fire is a new route to our players controller which means we have to add it to routes.rb in next step:
resources :players do as_routes put :fire, <code>:on</code> =>:member end
3. Let s move on to write a fire method for players controller:
def fire @record = find_if_allowed(params[:id], :update) begin @record.update_attributes!(:salary => 0) self.successful = true flash[:info] = 'player fired' rescue self.successful = false flash[:error] = 'Internal Error' end respond_to_action(:action_update) end
Last line includes a new feature: respond_to_action(:action_update), that code is responsible for updating the current record and showing any flash messages in your view.
You may start your application and you should see a fire action_link for each player s record.
4. Next step enables us to show ‘fire’ only if player is older than 6 years:
Firstly, we have to append an ignore_method parameter to our action link definition:
active_scaffold :player do |conf| conf.action_links.add 'fire', :confirm => 'are_you_sure', :type => :member, :method => :put, :position => false<strong>, :ignore_method => :ignore_fire_action?</strong> end
Secondly, we have to implement ignore_fire_action? in our player’s controller:
protected def ignore_fire_action?(record = nil) if record record.date_of_birth.since(6.years).to_date < Date.today else true end end
Great, we ve finished our task and can relax for the rest of the day. 🙂