开发者

rails join 2 tables HABTM

I'm using mysql & rails 3.0.9 I have two models: Type and Amenity each model is associated to the other with has_and_belongs_to_many and using a join table called amenities_types created as:

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

Now for instance I have the following records:

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

I would like to list开发者_如何学运维 the inner join table:

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

I tried Type.find(:all, :joins => :amenities) but only the type columns are shown the same if I do Amenity.find(:all ,:joins => :types) only the amenities columns are shown.


Modify your Amenity model as so:

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

then access like:

 Amenity.all.includes(:type)

To display:

Amenity.all.includes(:type).each { |a|
    puts a.label
    puts a.type.label
    # etc.
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜