Rails 模型,属于很多 [英] Rails Model, belongs to many

查看:30
本文介绍了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 :through,但我不确定在这种情况下它会如何工作.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.

推荐答案

rails 中的多对多关系不使用 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 =>false 需要在那里,因为我们不想要这个表上的主键.它将打破 Rails 关联.

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 :through.我写了一整篇文章,详细介绍了如何使用这两种方法以及何时使用每种方法:

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:

Rails 中的基本多对多关联

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

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

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

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