【问题标题】:FactoryGirl string together has_many relationships (i.e. User -> Blog -> Post )FactoryGirl 将 has_many 关系串在一起(即 User -> Blog -> Post )
【发布时间】:2012-10-11 21:56:04
【问题描述】:

假设我有三个模型:用户、博客和帖子。我的用户模型将具有:

User Model
  has_one :blog
  has_many :posts through: :blog


Blog Model
  belongs_to :user
  has_many :posts

Post 
  belongs_to :blog

当我做工厂时,我可以这样做:

FactoryGirl.define do
  factory :post do
    title "something"
    content "long text"
    blog 
  end
end

创建属于博客的帖子。我没有看到我应该在 :post 中输入的内容,以便 FactoryGirl 创建用户,然后创建属于该用户的博客,然后创建属于该博客/用户的帖子。我并没有在 FactoryGirl 的文档中看到任何内容来解决这个问题。

【问题讨论】:

    标签: ruby-on-rails-3 factory-bot rspec-rails


    【解决方案1】:
    FactoryGirl.define do
    
      factory :post do
        title "something"
        content "long text"
        blog 
      end
    
      factory :blog do
        user
        # blog attributes
      end
    
      factory :user do
        # user attributes
      end
    end
    

    然后

    @post = FactoryGirl.create(:post)
    @blog = @post.blog
    @user = @post.blog.user
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多