Ruby on rails Rails:如何创建具有两个“0”的模型;属于;关系,其中一个总是空的?
我有两个独立的模型:“页面”和“用户”。我希望有一个“评论”模型,可以在“页面”或“用户”上发表评论,但不能同时在两个页面上发表评论。我想这样做:Ruby on rails Rails:如何创建具有两个“0”的模型;属于;关系,其中一个总是空的?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有两个独立的模型:“页面”和“用户”。我希望有一个“评论”模型,可以在“页面”或“用户”上发表评论,但不能同时在两个页面上发表评论。我想这样做: class Comment < ActiveRecord::Base belongs_to :page belongs_to :user end class注释
class Comment < ActiveRecord::Base
belongs_to :page
belongs_to :user
end
class注释
但我不确定这是不是正确的方法。处理这个案子最好的办法是什么?看来你需要的是
class注释
以及迁移:
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
class CreateUsers
@NickM注释只能属于用户或页面。上述情况使得评论不可能同时属于这两个方面。@NickM实际上是这样的。在任何给定时间,注释将仅与用户
或页面
关联,但不能同时与两者关联。
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