[英]Rails: has_and_belongs_to_many with “master” record
我必須建模: User
和Post
。 每個用戶都可以“固定”(添加到他的頁面中)任何帖子,因此user.posts
應該返回所有添加的帖子和post.users
應該返回所有固定了該帖子的用戶。
用戶還應該能夠創建帖子,因此每個帖子都有一個創建者(“主”用戶),因此post.user
應該返回該主用戶(主用戶始終“固定”帖子)。
我的想法是像這樣使用遷移
create_table :posts_users do |t|
t.references :post, null: false, index: true
t.references :user, null: false, index: true
t.boolean :master, null: false, default: false
end
但是我應該如何在模型中指定關聯?
has_and_belongs_to_many
方法實際上只是has_many through
關系定義has_many through
的快捷方式,它不適合在中間聯接表中存儲任何其他數據。 將您的posts_users
重命名為pins
,我認為它可以像這樣工作:
class User < ActiveRecord::Base
has_many :pins
has_many :posts, through: :pins
has_many :master_posts, -> {where pins: {master: true}},
class_name: "Post", through: :pins, source: :post
end
class Pin < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
class Post < ActiveRecord::Base
has_many :pins
has_many :users, through: :pins
def user
users.where(pins: {master: true}).first
end
end
總的來說,這只是標准的has_many :through association
您幾乎在每個應用程序中都會遇到。 有趣的部分是master_posts
關聯。 您可以在documentation
了解傳遞的選項(請參閱底部的“ Options
部分)。
bob = User.create! name: "Bob"
bob.posts.create! title: "Title 1"
bob.posts.create! title: "Title 2"
bob.posts.pluck :title
# => ["Title 1", "Title 2"]
bob.master_posts.create! title: "Title 3"
bob.master_posts.create! title: "Title 4"
bob.master_posts.pluck :title
# => ["Title 3", "Title 4"]
bob.master_posts.last.user == bob
# => true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.