Rails的型号,属于多个 [英] Rails Model, belongs to many

查看:137
本文介绍了Rails的型号,属于多个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很难搞清楚我的模型如何协会的一项与另一倍数。

I'm having a hard time figuring out how to association one of my models with multiple of another.

因为它是现在,我有:

class ModelA < ActiveRecord::Base
  has_many :model_b
end

class ModelB < ActiveRecord::Base
  belongs_to :model_a
end

不过... ModelB必须属于不仅是MODELA的实例,但可能是三个。我知道有一个的has_many:穿越的,但我不知道它是如何在这种情况下工作。 MODELA的每个实例将始终有ModelB恰好三个实例。但正如前面所说,ModelB可以属于不止一个MODELA的实例。

However... ModelB needs to belong to not only one instance of ModelA, but possibly three. I know there is a has_many :through, but I'm not sure how it would work in this case. EVERY instance of ModelA will always have exactly three instances of ModelB. But as said before, ModelB can belong to more than just one instance of ModelA.

我知道这是令人困惑!

在此先感谢!

安德鲁戴维斯

推荐答案

在轨许多一对多的关系,不使用 belongs_to的。相反,你要使用的几个选项之一。首先是 has_​​and_belongs_to_many

Many-to-many relationships in rails don't use belongs_to. Instead, you want to use one of a couple options. The first is has_and_belongs_to_many:

# app/models/category.rb
class Category < ActiveRecord::Base
  has_and_belongs_to_many :items
end

# app/models/item.rb
class Item < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

和你需要添加额外的连接表在数据库中,有这样的迁移:

And you'll need to add an extra join table in your database, with a migration like this:

class AddCategoriesItems < ActiveRecord::Migration
  def self.up
    create_table :categories_items, :id => false do |t|
      t.integer :category_id
      t.integer :item_id
    end
  end

  def self.down
    drop_table :categories_items
  end
end

您可以看到,连接表的名称是其他两个表的名字的组合。该表必须按字母顺序排列如上面提到的,而:ID =&GT;假需要存在,因为我们不希望在这个表的主键。这将打破轨道关联。

You can see that the join table's name is the combination of the two other tables' names. The tables must be mentioned in alphabetical order as above, and the :id => false needs to be there, since we don't want a primary key on this table. It will break the rails association.

有也被称为另外,更复杂的方法的has_many:通过如果你需要存储有关关系本身的信息。我已经写了整篇文章,详细说明如何做到这两种方法,以及何时使用每个:

There's also another, more complex method known as has_many :through if you need to store info about the relationship itself. I've written a whole article detailing how to do both methods, and when to use each:

基本许多-to-many关联Rails中

我希望这会有所帮助,如果您有其他任何问题与我联系!

I hope this helps, and contact me if you have any other questions!

这篇关于Rails的型号,属于多个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆