Best way to do redirect_to using multiple controllers?

I’m using the same comment system for two different controllers, so
users post a comment to a game and a post using the same “create” action
in the comments controller.

I did comments for games first, so my comments create action looks like
this:

def create
@comment = Comment.new(params[:comment])
if @comment.save
flash[:notice] = “You have successfully added a comment.”
redirect_to :controller => ‘games’, :action => ‘show’, :id =>
@comment.game.id
else
render :action => ‘new’
end
end

What’s the best way to tell this action where the comment was posted, so
the redirect_to sends them back to the correct post or game?

Thanks!

On Jan 17, 2008, at 8:35 AM, Dave A. wrote:

What’s the best way to tell this action where the comment was
posted, so
the redirect_to sends them back to the correct post or game?

One thing you could do is put the destination info in the session,
then later redirect like this:

redirect_to :action => session[:back_action], :controller =>
session[:back_controller], :id => session[:back_id]

And of course earlier some other action had done something like this:

 session[:back_action] = "show"
 session[:back_controller] = "games"
 session[:back_id] = @comment.game.id

(untested)


-George

And of course earlier some other action had done something like this:

 session[:back_action] = "show"
 session[:back_controller] = "games"
 session[:back_id] = @comment.game.id

(untested)


-George

Thanks, that’s a good idea. The problem I’m having is that if I put that
code in my controller, let’s say in the action where the user can create
the comment, @comment doesn’t exist yet. But it’s a good start – I’ll
see what I can figure out.

Dave A. wrote:

And of course earlier some other action had done something like this:

 session[:back_action] = "show"
 session[:back_controller] = "games"
 session[:back_id] = @comment.game.id

(untested)


-George

Thanks, that’s a good idea. The problem I’m having is that if I put that
code in my controller, let’s say in the action where the user can create
the comment, @comment doesn’t exist yet. But it’s a good start – I’ll
see what I can figure out.

You could use a hidden field or (fields) in the forms.

<%= hidden_field_tag ‘from_controller’, ‘posts’ %>
<%= hidden_field_tag ‘from_id’, post_id %>

then in your controller…

redirect_to :controller => params[:from_controller], :action => ‘show’,
:id => params[:from_id]

You could use a hidden field or (fields) in the forms.

<%= hidden_field_tag ‘from_controller’, ‘posts’ %>
<%= hidden_field_tag ‘from_id’, post_id %>

then in your controller…

redirect_to :controller => params[:from_controller], :action => ‘show’,
:id => params[:from_id]

Yes, that did it. Thanks!