rails加入2桌HABTM

时间:2011-08-24 22:01:48

标签: mysql ruby-on-rails-3

我正在使用mysql& rails 3.0.9 我有两种型号:Type和Amenity 每个模型都与has_and_belongs_to_many相关联 并使用名为facilities_types的连接表创建为:

create_table :amenities_types, :id => false do |t|
    t.column :type_id, :integer
    t.column :amenity_id, :integer
end

现在我有以下记录:

types:
id label
1   a
2   b
3   c

amenities:
id  label
1   d
2   e

amenities_types
type_id amenity_id
1          1
1          2
3          2

我想列出内部联接表:

type.id type.label. amenity.id amenity.label
1         a           1           d
1         a           2           e
3         c           2           e

我尝试过Type.find(:all,:join =>:amenities),但只显示了类型列 同样如果我做Amenity.find(:all,:join =>:types),只显示了设施栏。

1 个答案:

答案 0 :(得分:0)

修改您的Amenity模型:

 class Amenity < ActiveRecord::Base
   has_one :type, :through => :amenities_types
 end

然后访问:

 Amenity.all.includes(:type)

显示:

Amenity.all.includes(:type).each { |a|
    puts a.label
    puts a.type.label
    # etc.
  }
相关问题