Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - render :action to target anchor tag?

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?

like image 339
ground5hark Avatar asked Jan 15 '10 01:01

ground5hark


3 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.

like image 176
ground5hark Avatar answered Nov 10 '22 04:11

ground5hark


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.

  1. 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

  2. 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.

like image 27
smugglerFlynn Avatar answered Nov 10 '22 05:11

smugglerFlynn


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.

like image 6
François Beausoleil Avatar answered Nov 10 '22 06:11

François Beausoleil