varatis
varatis

Reputation: 14740

Rails redirect_to not working, redirecting to show instead of custom action

So I have a ChatsController, and from my index action, I'm trying to redirect to a custom action, "decide":

def index
  @chat = Chat.customfind(params[:search])
  if(@chat.is_a?(Array))
    session[:chats] = @chat
    redirect_to :action => 'decide'
  else
  respond_to do |format|
    format.html { redirect_to @chat if [email protected]? }
  end
end

def decide
  @chats = session[:chats]
  @choice = Chat.find(params[:id])
  redirect_to @choice if [email protected]?
end

..where @choice is going to be decided by the params of the form on the decide page. But for some reason, instead of redirecting to decide, Rails redirects to show:

Started GET "/chats/decide" for 127.0.0.1 at 2012-03-14 17:13:36 -0400
  Processing by ChatsController#show as HTML
  Parameters: {"id"=>"decide"}
  ..............

Can anyone explain how to fix this?

Edit: I'm assuming this is what you want... the relevant parts of my routes.rb:

match "chats/decide" => "chats#decide"

resources :chats do
  member do
    post 'send_message'
  end
end

get "chats/logout"

..yeah it's a bit of a hodgepodge :/

Upvotes: 0

Views: 2491

Answers (1)

Graham Swan
Graham Swan

Reputation: 4828

It seems you are trying to achieve the following:

  • Find all chats matching a given search string
  • If 1 chat is found, redirect to it
  • If 2+ chats are found, redirect to /chats/decide so the user can pick one

I would implement this as follows:

1) Update routes.rb as follows:

resources :chats do
  member do
    post :send_message
  end

  collection do
    get :decide # Produces the '/chats/decide/' route
  end
end

2) Change your chats#decide action to this:

def decide
  @chats = session[:chats]
end

3) When you list the available chats in your decide.html.erb file, link them directly to the appropriate show link.

4) Be explicit about your redirect in chats#index:

redirect_to :controller => 'chats', :action => 'decide'

Your chats#decide action should not respond differently based on whether it's receiving an id or not. You can link directly to the specific chats in that view.

Upvotes: 1

Related Questions