我有一個帖子模型
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熱心網友回復:
下面是一個稍微隱藏的要求:
所以一個帖子可以再屬于 1 個級別,但我認為相同的 post_id 永遠不會與系統中的相同 level_id 相關聯。
這應該是可能的,所以這是一個要求。這意味著您將需要多對多關系。在模型上,您將使用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/398338.html
