Reputation: 653
How come when I have a link in my view file like this:
<%= link_to image_tag("foo.png"), :url => new_foo_path, :class => "banner-image" %>
The resulting markup produces an invalid anchor tag like this:
<a href="/home/index?class=banner-image&url=http%3A%2F%2Flocalhost%3A3000%2Ffoo%2Fnew"><img alt="foo" src="/assets/foo.png"></a>
But if I do this:
<%= link_to image_tag("foo.png"), url_for({:controller => "foo", :action => "new"}), :class => "banner-image" %>
It works perfectly - which produces this:
<a href="/foo/new" class="banner-image"><img alt="foo" src="/assets/foo.png"></a>
My routes.rb contains this line for foo:
resources :foo, only: [:new, :create]
Upvotes: 1
Views: 370
Reputation: 33646
Look at the source code: https://github.com/rails/rails/blob/797fcdf738a2a2772544731027d4fc5ca9d358bc/actionpack/lib/action_view/helpers/url_helper.rb#L174
This happens because in the first form you're essentially passing the url
& class
in the options
hash that the method accepts. In other words you're doing this:
<%= link_to image_tag("foo.png"), { :url => new_foo_path, :class => "banner-image" } %>
Passing additional key-values in the options
hash will append them as URL params in the final query string, thus the resulting markup in your first snippet.
But what you want to actually do is:
<%= link_to image_tag("foo.png"), { :url => new_foo_path }, { :class => "banner-image" } %>
which will pass the first hash as the options
hash and the second as the html_options
hash.
However as other have mentioned, you can just do:
<%= link_to image_tag("foo.png"), new_foo_path, :class => "banner-image" %>
which will pass the new_foo_path
as the value in :url
and { :class => 'banner-image' }
as the html_options
hash.
Upvotes: 3
Reputation: 5734
you can use the new_foo_path
directly in link_to
. No need to add :url =>
for it.
<%= link_to your-text-or-image-tag, your-path %>
For more please have a look on the link http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to.
Upvotes: 2