11

I have a user and story models which both of them have comments.

I declared the following models as below:

class Comment
  belongs_to :commentable, polymorphic: true
  belongs_to :user
end

class User
end

class Story
end

Now, I want to declare a comment object with FactoryGirl that belongs to the same user as commendable and as user.

Here is my code so far:

FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "person#{n}@exmaple.com"}
    sequence(:slug) {|n| "person#{n}"}
  end

  factory :comment do    
    occured_at { 5.hours.ago }
    user
    association :commentable, factory: :user
  end

end

The problem here is that the user that write the comment and the commendable user are not the same.

Why should I fix that?

Many TNX

4

2 回答 2

10

首先,我认为您还没有完成建立关联...我认为这就是您想要的:

class Comment < AR
  belongs_to :commentable, polymorphic: true
end

class User < AR
  has_many :comments, as: :commentable
end

class Story < AR
  has_many :comments, as: :commentable
end

见: http: //guides.rubyonrails.org/association_basics.html#polymorphic-associations

不要忘记数据库设置。

其次,出厂设置返回两个用户,因为您告诉它。尝试:

FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "person#{n}@exmaple.com"}
    sequence(:slug) {|n| "person#{n}"}
  end

  factory :comment do    
    occured_at { 5.hours.ago }
    association :commentable, factory: :user
  end

end

作为风格问题,模型名称的选择在这里有点混乱。用户如何“评论”?如果你的意思是其他类型的写作,我会选择一个不同的名字。如果您的意思是“用户个人资料”或类似的内容,则同上。

于 2012-08-07T16:34:55.073 回答
5

我遇到了这个问题,因为我个人有一个类似的问题并且刚刚解决了它。像@jordanpg 一样,我很好奇用户如何评论。如果我理解正确,问题在于撰写故事的用户和撰写故事评论的用户可能是不同的用户:

  • user_1 写了一个故事
  • user_2(或任何用户)可以评论 user_1 的故事

为了做到这一点,我会建立这样的模型关联:

# app/models/user.rb
class User < ApplicationRecord
  has_many :stories
  has_many :comments
end

# app/models/story.rb
class Story < ApplicationRecord
  belongs_to :user
  has_many :comments, as: :commentable
end

# app/models/comment.rb
class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :commentable, polymorphic: true
end

然后在我的工厂里,它看起来像这样:

# spec/factories.rb
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
于 2018-01-12T02:15:04.193 回答