【问题标题】:rails join 2 tables HABTM导轨连接 2 个表 HABTM
【发布时间】:2011-08-24 22:01:48
【问题描述】:

我正在使用 mysql & rails 3.0.9 我有两个模型:Type 和 Amenity 每个模型都通过 has_and_belongs_to_many 相互关联 并使用一个名为ities_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, :joins => :amenities) 但只显示类型列 如果我执行 Amenity.find(:all ,:joins => :types) 也一样,只显示便利栏。

【问题讨论】:

    标签: mysql ruby-on-rails-3


    【解决方案1】:

    修改您的舒适模型:

     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.
      }
    

    【讨论】:

    • 是否意味着我想将关联类型从“表连接”更改为“模型连接”?如果是这样,我需要声明设施类型模型吗?
    • 嗯...我从未明确声明过关联类型。如果使用上面的 sytnax,ActiveRecord 会自动生成需要的 sql join 语句。
    • 另外,不确定是否必须定义模型。 FWIW,我在我的代码中使用 has_one 关联到两个实体表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    相关资源
    最近更新 更多