[英]Passing an argument on request.referrer
I'm building a site where a link to fill a new form can be clicked from an Event show page
我正在建立一个网站,可以在
Event show page
单击填写新表格的链接
<%= link_to 'Be a Contestant', new_form_path(:event_id => @event.id)%>
This creates a link like 这会创建一个像
http://localhost:3000/forms/new?event_id=2
Now if the form is filled with an error, when submitted, it returns an error 现在,如果表单填写有错误,则在提交时会返回错误
Couldn't find Event with 'id'=""
So I decided to use the request.referrer
to redirect back to the previous page but it doesn't list the errors as use this method 因此,我决定使用
request.referrer
重定向回上一页,但由于使用此方法,因此未列出错误
def create
@form = Form.new(form_params)
respond_to do |format|
if @form.save
format.html { redirect_to @form, notice: 'Form was successfully created.' }
format.json { render :show, status: :created, location: @form }
else
format.html { redirect_to request.referrer }
format.json { render json: @form.errors, status: :unprocessable_entity }
end
end
end
I also tried this but to no avail. 我也尝试过,但无济于事。
def create
@form = Form.new(form_params)
respond_to do |format|
if @form.save
format.html { redirect_to @form, notice: 'Form was successfully created.' }
format.json { render :show, status: :created, location: @form }
else
format.html { redirect_to new_form_path(:event_id => request.referrer.params[:event_id]) }
format.json { render json: @form.errors, status: :unprocessable_entity }
end
end
end
What you probably really need to do is to add a hidden field event_id
to the form because I'm betting that event_id
doesn't get propagated from the #new
to the #create
action. 您可能真正需要做的是向表单添加一个隐藏字段
event_id
,因为我#new
event_id
不会从#new
传播到#create
动作中。
See here for more information on hidden_field_tag
在此处查看有关
hidden_field_tag
更多信息
You usually just render the edit
view when there was an error in create
: 通常,当
create
存在错误时,通常只渲染edit
视图:
def create
@form = Form.new(form_params)
respond_to do |format|
if @form.save
format.html { redirect_to @form, notice: 'Form was successfully created.' }
format.json { render :show, status: :created, location: @form }
else
format.html { render :edit, alert: 'Error creating ...' }
format.json { render json: @form.errors, status: :unprocessable_entity }
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.