简体   繁体   中英

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

I have two separate models: "page" and "user". I want to have a "comment" model that can comment on either a "page" or a "user", but not both at the same time. I want to do something like this:

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

but I'm not sure if that's the correct approach. What's the best way to handle this case?

It seems that what you need is Polymorphic Associations .

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

And the migrations:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM