Rails将连接表的约定命名为专用表

时间:2018-01-16 04:18:24

标签: ruby-on-rails

如果你有一个帖子和一个类别表,那么联接表将是posts_categories。但是,您可能有多种类别。

如果我们决定为每个对象类型创建专门的类别表,我们将创建一个posts_categories表,该表将是专门用于post对象的类别表。在posts和posts_categories之间调用多对多连接表会是什么?

2 个答案:

答案 0 :(得分:1)

如果我是你,我会创建包含其他列的连接表(categorizations):

rails g model Categorization post:references category:references new_column:new_type ....

### models/post.rb
class Post < ApplicationRecord
  has_many :categorizations
  has_many :categories, through: :categorizations
end

## models/categorization
class Categorization < ApplicationRecord
  belongs_to :post
  belongs_to :category

  ## You can add new columns as many as you want, just like other tables
end

# models/category.rb
class Category < ApplicationRecord
  has_many :categorizations
  has_many :posts, through: :categorizations
end

答案 1 :(得分:0)

我不确定我是否能完全理解你的问题。但是,如果你想在Post和Category之间建立多对多的关系,你可以尝试下面:

# post.rb
class Post < ApplicationRecord
   has_many :post_categories
   has_many :categories, through: :post_categories
end

#post_category.rb
class PostCategory < ApplicationRecord
   belongs_to :post
   belongs_to :category
end

# category.rb
class Category < ApplicationRecord
   has_many :post_categories
   has_many :posts, through: :post_categories
end

希望它有所帮助。