Misha Moroshko
Misha Moroshko

Reputation: 171341

Rails 3: Why "link_to" gives wrong output?

In my view file I type the following:

<table>
  <tr>
    <td><%= link_to(tag(:div, {:class => "my_class"}), "my_address") %></td>
  </tr>
</table>

The result is: (observed in Firebug)

<table>
  <tbody>
    <tr>
      <td>
        <a href="my_address"></a>
        <div class="my_class"></div>
      </td>
    </tr>
  </tbody>
</table>

Why the div is not inside a ?

Upvotes: 0

Views: 972

Answers (4)

Simone Carletti
Simone Carletti

Reputation: 176392

You should use content_tag, not tag.

<table>
  <tr>
    <td><%= link_to(content_tag(:div, { :class => "my_class" }), "my_address") %></td>
  </tr>
</table>

Honestly, in this case I prefer to use a block.

<table>
  <tr>
    <td>
    <%= link_to "my_address" do %>
      <div class="my_class"></div>
    <% end %>
    </td>
  </tr>
</table>

Rails doesn't perform any kind of HTML validation thus I didn't take into consideration the implication about valid/invalid HTML resulting from your code.

Upvotes: 2

Fareesh Vijayarangam
Fareesh Vijayarangam

Reputation: 5052

You cannot put block elements inside inline elements. If you are trying to link the div, you should use this:

 tag(:div, {:class => "my_class", :onclick => "my_address"})

Otherwise, use span instead of div

Upvotes: 0

Pravin
Pravin

Reputation: 6662

You can't have div inside a <a> tag. Use <span> or <p> instead

Upvotes: 0

McStretch
McStretch

Reputation: 20645

According to Is putting a div inside a anchor ever correct?, you can only place inline elements inside of an anchor. <div> is a block element, so your code will not work. You'll need to use something like <span> to wrap whatever data you intend to put in the anchor.

The first post does go on to say that HTML5 allows <a> to contain blocks though, so if you are defining HTML5 as your doctype then we need to dig deeper.

Upvotes: 2

Related Questions