Rails: render :action with an anchor tag

24th set 2012ruby, on rails, , , ,

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>&nbsp;
<div class="field"><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"

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"></fieldset>

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!

From one of my answers on Stackoverflow.com.