Mexxer
Mexxer

Reputation: 1777

Rails: Route to custom controller action

I have a really hard time understanding routes and I hope someone can help me.

Here's my custom controller

class SettingsController < ApplicationController
  before_filter :authenticate_user!

    def edit
      @user = current_user
    end

    def update
      @user = User.find(current_user.id)
      if @user.update_attributes(params[:user])
        # Sign in the user bypassing validation in case his password changed
        sign_in @user, :bypass => true
        redirect_to root_path
      else
        render "edit"
      end
    end
end

and I have the file settings/edit.html.erb and my link

<li><%= link_to('Settings', edit_settings_path) %></li>

The route

get "settings/edit"

doesn't work for this, because then I get

undefined local variable or method `edit_settings_path' for #<#<Class:0x00000001814ad8>:0x00000002b40a80>

What route do I have to give this? I can't figure it out. If I put "/settings/edit" instead of a path it messes up as soon as I'm on a other resource page because the resource name is put BEFORE settings/edit

Thx

Upvotes: 13

Views: 22318

Answers (2)

Dave Isaacs
Dave Isaacs

Reputation: 4539

If you want to explicitly define the route, you would use something like

get 'settings/edit' => 'settings#edit', :as => edit_settings

This statement defines that when a GET request is received for setting/edit, call the SettingsController#edit method, and that views can reference this link using 'edit_settings_path'.

Take some time to read the Rails guide on routing. It explains routing better than any other reference out there.

Also keep in mind the rake routes task, that lists the details of all the routes defined in your application.

Upvotes: 5

rubish
rubish

Reputation: 10907

Following should do:

get 'settings/edit' => 'settings#edit', :as => :edit_settings
# you can change put to post as you see fit
put 'settings/edit' => 'settings#update'

If you use /settings/edit directly in link, you shouldn't have problem with other resource name being prepended in path. However, without the leading slash, i.e. settings/edit it might have that issue.

Reason why edit_settings_path is not working might be because you didn't declare a named route. You have to use :as option to define by which method you will be generating this path/url.

Upvotes: 23

Related Questions