我有一个评论模型,它属于其他一些模型,比如Post、Page等,并且有一个(或者属于?)用户模型。但是我也需要用户可以评论,所以用户必须有很多来自其他用户的评论(这是多态的:可评论的关联),他必须有自己的评论,由他编写。
做这样的社团最好的办法是什么如果用户与注释有两种不同的关联,我如何在控制器中为用户读取和创建注释?
现在我这样做,我想是不对的:
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
最佳答案
您需要为该关联使用另一个名称。
has_many :comments, as: :commentable
has_many :commented_on, class_name: 'Comment' # you might also need foreign_key: 'from_user_id'.
See
has_many
's documentation online。在您的情况下不应该需要
foreign_key
,但我指出它只是以防万一在默认情况下,rails会猜测“{class_lowercase}u id”(因此在一个名为user的类中user_id
)。然后您可以访问这两个关联(显式需要
class_name
,因为rails无法从Comment
中找到commented_on
)。