Rails - render :action to target anchor tag?

Viewed 13402

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?

7 Answers

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.

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.

Use redirect_to so the the browser gets the heads-up to scroll to the anchor:

redirect_to :action => 'page', :anchor => 'form'

I'd suggest using jQuerys validate plugin. You could even implement your own form helpers that use jquery validate plugin depending on what object attributes you need to validate.

Of course it's more work, but I believe it would pay off in the future.

Other than that - use ajaxified submission and process error messages after response is received.

If you use JQuery, try to make some if condition that applies only after render and do this:

$('#anchor').get(0).scrollIntoView();
Related