Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl belongs_to association

I have a factory where I define a location in factories/locations.rb. I'm using Mongoid and Rails 3.1.1 with ruby 1.9.3.

FactoryGirl.define do
  factory :location do
      name Faker::Name.name
      description "Down by the river"
    end
end

And then I want to define a fitness camp which belongs_to a location (and therefore has a location_id attribute).

FactoryGirl.define do
  factory :fitness_camp do
    title "Parkour"
    association :location_id, :factory => :location
  end
end

This works but, is the result of my hacking, not what I read in the docs. From the getting started guide ( https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md) it seems this should be as simple as:

  factory :fitness_camp do
    title "Parkour"
    location
  end

Am I missing something? Does this indicate my models might not be configured correctly?

Thanks!

Tim

like image 404
bonhoffer Avatar asked Nov 13 '11 21:11

bonhoffer


1 Answers

I was an idiot -- I had validates_numericality_of :location_id

class FitnessCamp

  include Mongoid::Document

  field :title, :type => String

  belongs_to :location

  validates_presence_of  :location_id, :title
  validates_numericality_of :location_id

Mad props to Radar (Ryan Bigg) for helping me through this.

like image 128
bonhoffer Avatar answered Sep 22 '22 15:09

bonhoffer