views:

31

answers:

1

I'm allowing users to create a 'Question' from different pages in the app, and want them to be redirected to the right page after the new question is saved. Since one page has a params[:id] and one doesn't, I thought I'd use that to differentiate between the different redirects.

Here's what I was trying to do in my Questions controller:

respond_to do |format|  
if @question.save
    if params[:id].nil?
      format.html {redirect_to :controller => 'home', :action => 'show', :username => question.directed_to}  
    else
      format.html {redirect_to :controller => 'mentions', :action => 'show', :id => question.topic}
    end    
else
    ...
end

Thanks very much, I'm still new to this.

A: 

Relying on params beings nil is super awkward. You have control of the forms being submitted, so just sent an extra parameter yourself which identifies where it's coming from.

A few other things:

If you're only responding with html, don't bother doing the respond_to block.

if @question.save
  redirect_to :controller => 'home', :action => 'show', :username => question.directed_to
else
  redirect_to :controller => 'mentions', :action => 'show', :id => question.topic
end

@question.save doesn't run validations. It's pretty unusual that you'd want to have a create action that doesn't run validations. You should probably having something like:

def create
  @question = Question.new(params[:question])
  @question.save!
  flash[:notice] = "Question saved successfully"
  # Do your redirects here
rescue ActiveRecord::RecordInvalid
  flash[:error] = "There were errors saving your question"
  render :action => :new
end
Jamie Wong
What do you mean by 'send (set?) an extra parameter to identify where it's coming from'? I could run a migration to add an extra attribute to the Questions model (like :type_of_question), and then set the value of that attribute in the form, but is that really necessary?
kateray
It doesn't have to be an attribute of the Questions model. You could do something like `hidden_field_tag 'source', 'page1'` which you can access with `params[:source]`. Since this isn't passed as part of `params[:question]`, it doesn't need an `attr_accesor` on the Questions model.
Jamie Wong
Thanks, worked perfectly!
kateray
@kateray Awesome. If you don't have any more questions and everything is working correctly, please accept the answer.
Jamie Wong
Hmm, one issue: I can't say 'render :action => :new' when there are errors because I need to redirect back to the same places I do when the question saves correctly. However, calling a 'redirect' rather than a 'render' seems to make me lose all my custom error messages (like what happened here: http://stackoverflow.com/questions/2638215/rails-does-not-display-error-messages-on-a-form-in-a-custom-method).I know that's a slightly different question....
kateray