Alex Rivera | Logout

Rails - render :action to target anchor tag?

Asked 2010-01-15T01:34:53.830
32

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?

Edit
Report

1 Answer

2

You can use unobtrusive jQuery and a data-attribute.

For example in my app I have a big form with, among the others, an "address" fieldset in which the user should:

  • write his address and then
  • hit a "check" button to display a little google map to see if the address he entered is correct.

Of couse after he its the "check" button I want to render the form again but with the ancor to this address fieldset, where the map is displayed.

This is my .erb template:

<fieldset id="address" data-preview="<%= params[:preview] ? true : false -%>">    
<legend>Write you address here, then check it</legend> 
  <div class="field"> 
    <%= f.text_field :address %>
    <input id="preview-button" type="submit" name="preview" value="check">
  </div>
 </fieldset>

When the check button is hit, it will set params[:preview]. In my controller, the create action looks like this:

def create   
  @obj = current_user.objs.new(params[:obj]) 
  if params[:preview] 
    # geocoding code, and then:
    render action: "edit" 
  else
    #...
  end
end                           

So the action edit will be rendered with params[:preview] still defined, and this will set the #address fieldset data-preview to true. Namely, this line of HTML will be rendered:

<fieldset id="address" data-preview="true">

Now all I need to do is to fetch that information through javascript and if data-preview is true move window location to the #address anchor. Here is my unobtrusive jQuery code:

$(function() {
  var preview = $("#address").data('preview');
  if (preview == true){
    window.location = window.location.href + "#address";
  }; 
}); 

And that's it!

answered 2012-09-24T11:13:43.223

Your Answer