I'm building a site where a link to fill a new form can be clicked from an 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
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.
See here for more information on hidden_field_tag
You usually just render the edit
view when there was an error in create
:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.