Rails 多态关联和 has_many 同一模型
Rails polymorphic association and has_many for the same model
我有 Comment 模型,它属于其他一些模型,如 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
您需要为该协会使用另一个名称。
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}_id”(因此 user_id
在 class 命名用户中)。
然后您可以访问两个关联(明确需要 class_name
因为 Rails 无法从 commented_on
中找到 Comment
)。
我有 Comment 模型,它属于其他一些模型,如 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
您需要为该协会使用另一个名称。
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}_id”(因此 user_id
在 class 命名用户中)。
然后您可以访问两个关联(明确需要 class_name
因为 Rails 无法从 commented_on
中找到 Comment
)。