我正在使用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),只显示了设施栏。
答案 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.
}