Rails 3:如何在视图中显示多对多联接? [英] Rails 3: How to display many-to-many join in view?

查看:134
本文介绍了Rails 3:如何在视图中显示多对多联接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在视图中显示每个行程"的所有腿".

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 

模型是多对多的.我有三个表Legs,Trips和Legs_trips.这些模型如下所示:

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.

提前谢谢!

詹姆斯

推荐答案

尝试

 <% @trips.each do |trip| %>
   <ul>
     <li>
       <%= trip.name %>
         <% trip.legs.each do |leg| %>
            <li>
              <%= leg.name %>
            </li>
         <% end %>
     </li>
   </ul>
 <% end %>    

这篇关于Rails 3:如何在视图中显示多对多联接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆