In a rails 4.1.5 app, views/posts/new.html.erb
contains some content before the actual form. So, I want the new
action to go to posts/new#form_id
where the form element's id is form_id
.
How do I achieve this?
I have seen posts that suggest a redirect with anchor: 'form_id'
, but since I would call this from the same action, I would go into a redirect loop.
I also considered changing this in the routes, but the route DSL has a special meaning for '#'
.
Update 1:
I can think of two options:
a) redirect in the action:
views/posts/new.html.erb
def new
@post = Post.new
if params[:anchor] == 'form_id'
render 'new'
else
redirect_to new_post_path(anchor: 'form_id')
end
end
Turns out this won't work because 1) anchor is not available on the server, and 2) without that, redirecting to the route with anchor will keep coming back to the same action handler.
b) In routes, override new and edit to append an anchor tag - something like:
routes.rb resources :posts do get 'new', to: 'new#form_id' get 'new', to: 'edit#form_id' end
But b will not work, since the '#' is interpreted as controller#action
in this context.
Update 2: A third option: use ajax on the page:
I tried the below two AJAX options, and in both cases it does jump to the anchor tag, but it doesn't align the tag to the top of the page (the form shows up midway down the page) - even though I have at least two pages of content above the form, the form shows up misaligned from the top:
2a
<script>
$(document).load(function() {
$('html, body').animate({
scrollTop: $("#form-header").offset().top
}, 2000);
});
};
2b
<script>
$(document).load(function() {
window.location = window.location.href + '#form-header';
};