Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 redirect_to pass params to a named route

Tags:

ruby

I am not finding much info on how to do this even though there are lots of suggestions on how to pass params to a redirect using hashs like this redirect_to

:action => 'something', :controller => 'something'

in my app I have the following in the routes file

match 'profile'   =>  'User#show'

my show action loos like this

def show
 @user = User.find(params[:user])
  @title = @user.first_name
end

the redirect happens in the same user controller like this

   def register
    @title = "Registration"
    @user = User.new(params[:user])

    if @user.save
      redirect_to  '/profile'
    end
  end

The question is in the register action when I redirect_to how do I pass along the params so I can grab that user from the database or better yet ... I already have a user variable so how do I pass along the user object to the show action?

-matthew

like image 517
mattwallace Avatar asked Dec 14 '10 15:12

mattwallace


2 Answers

If you're doing a redirect, Rails will actually send a 302 Moved response with a URL to the browser and the browser will send another request to that URL. So you cannot "pass the user object" as in Ruby, you can only pass some url encoded parameters.

In this case you would probably want to change your routing definition to:

match 'profile/:id' => 'User#show'

and then redirect like this:

redirect_to "/profile/#{@user.id}"
like image 195
Matt Avatar answered Oct 31 '22 14:10

Matt


First off, I'd name your route, to make using it easier:

match '/profile/:id' => 'users#show', :as => :profile

You would then redirect to it, like so:

redirect_to profile_path(@user) # might have to use profile_path(:id => @user.id)

Then to pull the user from the database:

def show
  @user = User.find(params[:id]) # :id comes from the route '/profile/:id'
  ...
end

As an aside, if you use something like Devise for authentication, it provides you with a current_user method, and therefore you wont need to pass around the user's id:

match '/profile' => 'users#show', :as => :profile

redirect_to profile_path

def show
  @user = current_user
end
like image 35
jswanner Avatar answered Oct 31 '22 15:10

jswanner