[英]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. 由于一页包含params [:id],而另一页没有params [:id],所以我认为我可以使用它来区分不同的重定向。
Here's what I was trying to do in my Questions controller: 这是我在Questions控制器中尝试执行的操作:
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. 依靠参数众生nil超级笨拙。 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. 如果您仅使用html进行响应,则不必理会response_to块。
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. @question.save
不运行验证。 It's pretty unusual that you'd want to have a create action that doesn't run validations. 您想要具有不运行验证的create动作是非常不寻常的。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.