user1573607
user1573607

Reputation: 522

Rails - Add action to controller created by scaffold

I'm trying to add an action called rollback to controller. As I've seen, the only things I should do is writting the new action:

def rollback
    puts "ROLLBACK!"
    respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @components }
end

Modify the routes.rb file:

resources :components do
   collection do
      post :rollback, :as => 'rollback'
   end
end

And calling the action from some view:

<%= link_to 'Rollback', rollback_components_path %>

But I get the following error:

Couldn't find Component with id=rollback
app/controllers/components_controller.rb:18:in `show'

That's because instead of going to rollback action, the controller thinks that we are trying to 'show' to component with id 'rollback'.

Something that it seems weird for me is that calling 'new' action rails uses new_component_path (without s, in singular), but if I write rollback_component_path it throws me an error and I cant see the view.

Upvotes: 0

Views: 1092

Answers (2)

Andreas Lyngstad
Andreas Lyngstad

Reputation: 4927

This will work

routes.rb

resources :components
match "components/rollback" => "components#rollback",  :as => :rollback

In views

<%=link_to 'Rollback', rollback_path%>

Upvotes: 1

nathanvda
nathanvda

Reputation: 50057

In your routes you require a POST, just clicking a link is by default a GET, so either write

resources :components do
  collection do
    get :rollback
  end
end

and then the link_to will work as expected.

I am assuming the rollback operation is not idempotent, so a POST is semantically better in that case.

If you write your link as follows, then rails will create an inline form for you:

link_to 'Rollback', rollback_components_path, :method => 'post'

Hope this helps.

Upvotes: 1

Related Questions