我看到了这个问题因为我个人有一个类似的问题并解决了它。像@jordanpg一样,我很好奇一个用户如何可评论。如果我理解正确,问题是写故事的用户和评论故事的用户可能是不同的用户:
- user_1 写了一个故事
- user_2(或任何用户)可以评论 user_1 的故事
为了做到这一点,我会设置以下模型关联:
class User < ApplicationRecord
has_many :stories
has_many :comments
end
class Story < ApplicationRecord
belongs_to :user
has_many :comments, as: :commentable
end
class Comment < ApplicationRecord
belongs_to :user
belongs_to :commentable, polymorphic: true
end
在我的工厂里,它会是这样的:
FactoryBot.define do
factory :user do
sequence(:email) {|n| "person#{n}@example.com"}
sequence(:slug) {|n| "person#{n}"}
end
factory :story do
body "this is the story body"
user
end
factory :comment do
body "this is a comment on a story"
user
association :commentable, factory: :story
end
end
这个做法的一部分原因在于
factory_bot
会自动构建您正在创建的任何子对象的父对象。他们关于关联的文档相当不错:
http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Associations
如果您需要让用户能够对评论进行评论,则可以这样做:
factory :comment_on_story, class: Comment do
body "this is a comment on a story"
user
association :commentable, factory: :story
end
factory :comment_on_comment, class: Comment do
body "this is a comment on a comment"
user
association :commentable, factory: :comment_on_story
end