簡體   English   中英

Rails:具有“主”記錄的has_and_belongs_to_many

[英]Rails: has_and_belongs_to_many with “master” record

我必須建模: UserPost 每個用戶都可以“固定”(添加到他的頁面中)任何帖子,因此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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM