Rails 3,如何通过不保存的 Controller#create 操作设置和传递查询字符串
我有 3 个视图,用户在订单中看到,首先他们选择一个位置,接下来选择一个类别,然后他们被发送到一个表单。第一个视图将位置信息发送到类别选择视图。在类别选择视图中,我使用查询字符串将类别 ID 发送到表单。在 Controller#new 操作中,我将查询字符串放入实例变量中: @award = Award.find(params[:award])
问题是,如果用户没有填写适当的字段,则表单不会' t 保存,查询字符串不再存在。在我的例子中,这意味着推荐不再有类别,这将继续使表单失败。
如何通过失败的创建操作保留查询字符串?
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
编辑_
我想我可以将新操作分享给:
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
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. 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. In the Controller#new action I am putting the query string into an instance variable: @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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

好吧,由于查询字符串已经从新操作传递到创建操作,因此如果创建操作失败,它将命中您的 'format.html { render action: "new" }' 行。
你可以这样做:
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.
you could do something like this: