I have a helper which instantiates a model and renders a form. This form should be available to any view in the application
# support_form_helper
def support_form
@support_stats = SupportForm::Stat.find(get_stats_id)
@enquiry = SupportForm::Enquiry.new(stats_id: @support_stats.id)
render partial: 'support_form/enquiries/form'
end
And its rendered in the view:
# some_view.html.erb
<%= support_form %>
This is fine until I want to submit the form and validate it in the controller.
# enquiries_controller.rb
def create
@enquiry = SupportForm::Enquiry.new(params[:support_form_enquiry])
topic = @enquiry.topic
@stat = SupportForm::Stat.find(@enquiry.stats_id)
@stat.stats[topic] = @stat.stats[topic].to_i.next
respond_to do |format|
if @enquiry.valid? && @stat.save
format.html { redirect_to(root_path) }
else
format.html { redirect_to(:back) }
end
end
end
This is where I can't render the previous view with the errors attached to the invalid object. The helper gets invoked again and initializes a new @enquiries
object, without the errors obviously.
How can I render the form in many views across an application and still return to the view with the object together with errors when it is invalid?
I found an answer which answers my question but its a bad idea:
Render the action that initiated update
def create @enquiry = SupportForm::Enquiry.new(params[:support_form_enquiry])
topic = @enquiry.topic
@stat = SupportForm::Stat.find(@enquiry.stats_id)
@stat.stats[topic] = @stat.stats[topic].to_i.next
if @enquiry.valid? && @stat.save
redirect_to(root_path)
else
render Rails.application.routes.recognize_path(request.referer).values.join("/")
end
end
The problem is that there will likely be instance variables in the view that submitted the form and I would have to be able to instantiate all the instance variable in the application then.....not possible.
Currently I'm considering putting the errors in the flash hash... not something I want to do. With the original object returned i can repopulate the fields with the users input.