2

I'm trying to display all the 'legs' for each of my 'trips' in my view.

Ideally they would look like this:

-Trip1.name
  - Leg1.name
  - Leg2.name
  - Leg3.name
-Trip2.name
  - Leg4.name
  - Leg5.name
  - Leg6.name 

The models are many-to-many. I have three tables Legs, Trips and Legs_trips. The models look like this:

Trip.rb

class Trip < ActiveRecord::Base
 has_and_belongs_to_many :legs
 accepts_nested_attributes_for :legs, :reject_if => :all_blank
end

Leg.rb

class Leg < ActiveRecord::Base
 has_and_belongs_to_many :trips
 validates_uniqueness_of :name
 accepts_nested_attributes_for :trips
end

There is nothing but this in the controller at the moment:

def index
@trips = Trip.all
@legs = Leg.all

 respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @trips }
 end
end

Any suggestions for how to structure my view would be great! I've tinkered around for ages but can't seem to get anywhere near or find anything online.

Thanks in advance!

James

4

2 回答 2

3

try

 <% @trips.each do |trip| %>
   <ul>
     <li>
       <%= trip.name %>
         <% trip.legs.each do |leg| %>
            <li>
              <%= leg.name %>
            </li>
         <% end %>
     </li>
   </ul>
 <% end %>    
于 2012-07-05T11:38:48.213 回答
2

In you view apply them like this:

<ul>
<% @trips.each do |trip| %>
  <li>
  <%= tri.name %>

  <ul>
  <% @trips.legs.each do |leg_in_trip| %>
    <li>
    <%= leg_in_trip.name %>
    </li>
  <% end %>
  </ul>
  </li>
<% end %>
</ul>
于 2012-07-05T11:34:01.073 回答