[英]rails 3, How to set and pass a query string through an Controller#create action that doesn't save
I have 3 views that the users sees in an order, first they select a location, next then select a category, then they get sent to a form. 我有3个用户按顺序查看的视图,首先,他们选择一个位置,然后选择一个类别,然后将他们发送到表单。 The first view sends the location info to the category select view.
第一个视图将位置信息发送到类别选择视图。 From the category select view, I am using a query string to send the category id through to a form.
从类别选择视图中,我正在使用查询字符串将类别ID发送到表单。 In the Controller#new action I am putting the query string into an instance variable: @award = Award.find(params[:award])
在Controller#new动作中,我将查询字符串放入实例变量中:@award = Award.find(params [:award])
the issue is that if the user does not fill in the appropriate fields, then the form doesn't save, and the query string no longer exists. 问题是,如果用户未填写适当的字段,则表单不会保存,并且查询字符串不再存在。 Which in my case means that a recommendation doesn't have a category anymore which will then continue to make the form fail.
在我的情况下,这意味着建议不再具有类别,该类别将继续使表单失败。
How can I persist the query string through a failed create action? 如何通过失败的创建操作来保留查询字符串?
def create
@recommendation = Recommendation.new(params[:recommendation])
@recommendation.user_id = current_user.id
respond_to do |format|
if @recommendation.save
format.html { redirect_to location_path, notice: 'Recommendation was successfully created.' }
format.json { render json: @recommendation, status: :created, location: @recommendation }
else
format.html { render action: "new" }
format.json { render json: @recommendation.errors, status: :unprocessable_entity }
end
end
end
EDIT _ 编辑_
I figured I could share the new action to: 我想可以将新操作分享给:
def new
@recommendation = Recommendation.new
@award = Award.find(params[:award])
@recommendation.approvals.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @recommendation }
end
end
well, since the querystring is already being passed from the new action to the create action, if the create action fails, it will hit your 'format.html { render action: "new" }' line. 好吧,因为查询字符串已经从新动作传递到了create动作,所以如果create动作失败,它将命中您的'format.html {render action:“ new”}'行。
you could do something like this: 您可以执行以下操作:
format.html {redirect_to thing_path(@thing, :foo => params[:foo])}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.