繁体   English   中英

表如何加入Rails 4?

[英]How do tables join in Rails 4?

我有以下模型:

class A < ActiveRecord::Base
    has_and_belongs_to_many :Bs
end

class B < ActiveRecord::Base
    has_and_belongs_to_many :As
end


class CreateAs < ActiveRecord::Migration
  def change
    create_table :as do |t|
      t.string :name
      t.timestamps null: false
    end
  end
end

class CreateBs < ActiveRecord::Migration
  def change
    create_table :bs do |t|
      t.string :name
      t.timestamps null: false
    end
  end
end

如果表“ as”具有以下条目:

  1. “ A1”
  2. “A2”
  3. “ A3”

表“ bs”具有以下条目:

  1. “ B1”
  2. “ B2”
  3. “ B3”

表“ as”的外键是否为b,反之亦然?

如果是,那么在Rails 4中如何进行内部映射? 它将如何映射? 以及如何加入和显示这两个表?

该表没有外键,因为它具有has_and_belongs_to_many关系-它们将通过您需要创建的新联接表链接:

rails generate migration CreateJoinTableAB a b

您将需要为此创建一个联接表。 就像是:

class CreateJoinTableAB < ActiveRecord::Migration
  def change
    create_join_table :as, :bs do |t|
      # add some idexes depending on your use case
      # t.index :a_id
      # t.index :b_id
    end
  end
end

在《 Rails指南》中阅读有关此内容的更多信息。

请参阅《 Rails指南》中的has_and_belongs_to_many。 在那里描述。 带有关于数据库结构的漂亮图片。

http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM