gpt4 book ai didi

ruby-on-rails - Rails : How do I create a model with two "belongs_to" relations, 其中一个总是空的?

转载 作者:数据小太阳 更新时间:2023-10-29 08:37:30 25 4
gpt4 key购买 nike

我有两个独立的模型:“页面”和“用户”。我想要一个“评论”模型,可以对“页面”或“用户”发表评论,但不能同时对两者发表评论。我想做这样的事情:

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

但我不确定这是否是正确的方法。处理这种情况的最佳方法是什么?

最佳答案

看来你需要的是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

和迁移:

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

关于ruby-on-rails - Rails : How do I create a model with two "belongs_to" relations, 其中一个总是空的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27495857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com