拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何为可以分配到1个或多个级别的Post物件建模

如何为可以分配到1个或多个级别的Post物件建模

白鹭 - 2022-01-26 1958 0 0

我有一个帖子模型

class Post < ApplicationRecord
    belongs_to :account
end

迁移看起来像:

class CreatePosts < ActiveRecord::Migration[7.0]
  def change
    create_table :posts do |t|
      t.integer :account_id, null: false
      t.string :title, null: false
      t.string :content, null: false

      t.timestamps
    end
  end
end

现在,当我显示这些帖子的串列时,我只会根据用户的许可来显示它们。

class Level< ApplicationRecord
end

class CreateLevels < ActiveRecord::Migration[7.0]
  def change
    create_table :levels do |t|
      t.integer :account_id, null: false
      t.string :name, null: false         

      t.timestamps
    end
  end
end

所以说我有用户权限建模为级别:

Level 1
Level 2
Level 3

因此,每次创建帖子时,它都会被分配到这些级别中的 1 个以上。

当级别为 2 的用户查看帖子串列时,该用户只会看到与级别 2 关联的帖子。

我猜这张桌子看起来像:

- post_id
- level_id
- timestamps

所以一个帖子可以再属于 1 个级别,但我认为相同的 post_id 永远不会与系统中的相同 level_id 相关联。

在 Rails/ActiveRecord 中,哪种型别的关联最能描述这一点?

如果有人可以帮助调整我的迁移并将适当的关联添加到模型中。

uj5u.com热心网友回复:

下面是一个稍微隐藏的要求:

这应该是可能的,所以这是一个要求。这意味着您将需要多对多关系。在模型上,您将使用has_and_belongs_to_many.

更多信息可以在这个 Stack Overflow 问题上找到,专门询问多对多关系:在 Rails 中创建多对多关系

uj5u.com热心网友回复:

我可能会这样建模:

迁移

create_table :users do |t| 
  t.string :username, null: false
  t.timestamps
end 
create_table :posts do |t| 
  t.references :author, foreign_key: { to_table: :users }
  t.string :title, null: false
  t.string :content, null: false
  t.timestamps
end 
create_table :levels do |t| 
  t.string :name, null: false
  t.timestamps
end 
create_table :post_levels do |t| 
  t.references :level
  t.references :post
  t.timestamps
end 
add_reference(:users, :level)

楷模

class User 
  belongs_to :level 
  has_many :authored_posts, class_name: 'Post', foreign_key: :author_id
  has_many :viewable_posts, through: :level, source: :posts
end 

class Post 
  belongs_to :author, class_name: 'User'
  has_many :post_levels
  has_many :levels, through: :post_levels
end 

class Level 
  has_many :users 
  has_many :post_levels
  has_many :posts, through: :post_levels
end 

class PostLevel
  belongs_to :level
  belongs_to :post 
 
  # make sure a post can only belong to a level one time 
  validates :post_id, uniqueness: {scope: :level_id}
end 
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *