开发者

How do I write a conditional redirect into a model's create method, in a Rails app?

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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜