簡體   English   中英

Rails:如何創建具有兩個“ belongs_to”關系的模型,其中一個始終為空?

[英]Rails: How do I create a model with two “belongs_to” relations, one of which is always empty?

我有兩個單獨的模型:“頁面”和“用戶”。 我想要一個可以在“頁面”或“用戶”上評論的“評論”模型,但不能同時評論兩個模型。 我想做這樣的事情:

class Comment < ActiveRecord::Base
  belongs_to :page
  belongs_to :user
end

但我不確定這是否正確。 處理此案的最佳方法是什么?

看來您需要的是多態關聯

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

class User < ActiveRecord::Base
  has_many :comments, as: :commentable
end


class Page < ActiveRecord::Base
  has_many :comments, as: :commentable
end

以及遷移:

class CreateUsers < ActiveRecord::Migration   # and similar for Pages
  def change
    create_table :users do |t|
      ...
      t.references :commentable, polymorphic: true
      ...
    end
  end
end

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      ...
      t.integer :commentable_id
      t.string  :commentable_type
      ...
    end
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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