Question

I was doing a project in rails. Rails has its own powerful tags in views. But are little bit confusing.I want two elements inside the anchor tag. That is

   <li>
      <a href="#">
        <h2>Task Name</h2>
        <p>Task Content #5</p>
      </a>
    </li> 

This to be changed to link_to tag.

    <% @tasks.each do |task| %>
    <li id="task_<%= task.id %>">
        <%= link_to(task.task_name,{:action => 'show',:id => task.id}) %>
    </li>
    <% end %>

But I dont know how to add both p tag and h tag inside the link_to in rails.Please help me. I am new to rails.

Was it helpful?

Solution

You can wrap it like this:

<% @tasks.each do |task| %>
    <li id="task_<%= task.id %>">
        <%= link_to task_path(task.id) do %>
            <h2><%= task.task_name %></h2>
            <p><%= task.task_content %></p>
        <% end %>
    </li>
<% end %>

You could be even fancier and create your html tags with content_tag

<% @tasks.each do |task| %>
    <li id="task_<%= task.id %>">
        <%= link_to task_path(task.id) do %>
            <%= content_tag :h2, task.task_name %>
            <%= content_tag :p, task.task_content %>
        <% end %>
    </li>
<% end %>

Hope it helps :)

OTHER TIPS

Use

<%= link_to {:action => 'show',:id => task.id} do %>
     any contents that you want inside the link
<% end %>

to put more elements inside the link

<% @tasks.each do |task| %>
  <li id="task_<%= task.id %>">
     <%= link_to {:action => 'show',:id => task.id} do %>
        <h2>Task Name</h2>
        <p>Task Content #5</p>
     <% end %>
  </li>
<% end %> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top