I'm looking to use render like so:
render :action => 'page#form'
I also tried this:
render :template => 'site/page#form'
That didn't work either. The form on this particular page is at the very bottom, and if any errors occur on submission I'd hate for the user to be defaulted to the top of the page. I also need to use render (not redirect) because I need to retain the objects and their errors.
How can I render to target a specific anchor tag?
Believe I found a solution. For anyone else having this issue, pointing the form like so:
<%= form_tag '/page#form' do %>
Seems to have solved the problem.
Quick summary on bobthabuilda's answer, for those not-so-bright folks like myself who recently googled into that question and can't seem to get the trick.
First of all, abstracting from Rails, every basic HTML <form>
has an option to add anchor to the target page, and for this to work you basically leave the anchor in the 'action'
attribute, like this:
<form action="/contact#form" method="post">
...
</form>
That way, upon submit, your browser will use a /contact#form
request, which will throw you right to the specified anchor.
What we need to do now is simply make rails generate our form tag the correct way, as in example above. This will require us to modify our view in two possible ways.
If you use form_tag
in your view, use it the way bobthabuilda suggested:
<%= form_tag '/contact#form' do %>
Simple as that, you just tell rails to set action of our form to /contact#form
If you use form_for
, there is an :anchor
parameter, which goes into specified :url
like this:
<%= form_for @message,
:url => contact_path(@message, :anchor => 'form') do |form| %>
or like this (if you rely on :action
):
<%= form_for(@message,
:url => { :action => "create" , :anchor => "form" }) do |form| %>
This way rails will create correct action for the HTML form, and will add our anchor at the end of it afterwards.
Use JavaScript to move the view to the right place. There's no way I know of to do otherwise.
<script>
window.location = window.location.href + "#form";
</script>
Untested, but I think this should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With