【发布时间】:2017-01-06 11:59:02
【问题描述】:
我有属于其他一些模型的评论模型,如 Post、Page 等和 has_one(或 belongs_to?)用户模型。但是我也需要用户可以评论,所以用户必须有很多来自其他用户的评论(这是多态的:可评论关联),他必须有自己的评论,由他编写。 建立这样的协会的最佳方式是什么?如果用户与评论有两种不同的关联,我如何在控制器中为用户阅读和创建评论? 现在我这样做了,我猜这是不对的:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :comments, as: :commentable
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :user
end
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :content
t.references :commentable, polymorphic: true, index: true
t.belongs_to :user
t.timestamps null: false
end
end
end
【问题讨论】:
标签: ruby-on-rails ruby polymorphic-associations