在FactoryGirl中创建HABTM关系?

时间:2015-12-01 11:02:34

标签: ruby-on-rails ruby ruby-on-rails-4 factory-bot

我有以下内容:

    class Group < ActiveRecord::Base
      has_and_belongs_to_many :users
      has_many :permissions
      has_one :city
    end


    class User < ActiveRecord::Base
      has_many :permissions, dependent: :destroy
      has_and_belongs_to_many :groups
    end

    FactoryGirl.define do
      factory :user do
        username            { FFaker::Name.first_name }
        email               { FFaker::Internet.email }
        first_name          { FFaker::Name.first_name }
        last_name           { FFaker::Name.last_name }
        current_login_ip "127.0.0.1"
        login_count         { rand(100) + 1 }
        deleted_at nil
        updated_at          { FactoryGirl.generate(:time) }
        created_at          { FactoryGirl.generate(:time) }
        suspended_at nil
        password "password"
        password_confirmation "password"
        vertical {1}
        marketplace_role {1}
      end

      factory :admin do
        admin true
      end


      factory :group do
        users { |a| [a.association(:user)] }
        name                { FFaker::Company.name }
        city                { FactoryGirl.create(:city) }
      end
    end

    FactoryGirl.define do
      factory :permission do
        user
        group
        asset               { fail "Please specify :asset for the permission" }
        updated_at          { FactoryGirl.generate(:time) }
        created_at          { FactoryGirl.generate(:time) }
      end
    end

 factory :city do
    name              { FFaker::Name.name }
  end

  factory :zone do
    city
    name              { FFaker::Name.name }
  end

  factory :location do
    zone
    name              { FFaker::Name.name }
  end
  

失败/错误:@group = FactoryGirl.create(:group)   ActiveModel :: MissingAttributeError:无法写入未知属性   GROUP_ID

这就是我得到的。我无法定义和使用组工厂。我查看了这个post,但解决方案无效。

1 个答案:

答案 0 :(得分:1)

将城市工厂更改为以下

 factory :city do
    group             nil # or group_id if you will
    name              { FFaker::Name.name }
  end

你很可能会很好。