Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set up my fixtures for a has_and_belongs_to_many relation?

I have the following models:

class Company < ActiveRecord::Base
  has_and_belongs_to_many :regions

class Region < ActiveRecord::Base
  has_many :requests
  has_and_belongs_to_many :companies

class RequestForProposals < ActiveRecord::Base
  belongs_to :region

Whenever I get a new request, I want to send a notification to the companies active in the same region.

How do I set this up in my fixtures so that I can unit test the logic of finding the right companies?

I've tried

region_ids: 1, 2
regions: one, two

in companies.yml, but neither works in assigning regions to the companies.

Here is a gist of the SQL generated: https://gist.github.com/2713518

like image 977
Peter Evjan Avatar asked May 14 '12 06:05

Peter Evjan


1 Answers

For

regions: one, two

in companies.yml to work you need to let rails auto assign the ids for the regions. This is because (in order to avoid having to have read regions.yml before companies.yml) rails calculates the ids it sticks in the join table from the names of the companies fixtures. if you've assigned the ids yourself, they won't match up with the calculated ones.

From the sql you've provided it looks like you're setting the ids on the regions to 1 and 2, i.e. your regions.yml has

one:
  id: 1
  name: MyString 

Remove the id:1 and you should be ok. You'll also need to update any other files (e.g. request_for_proposals.yml) that refer to regions, replacing

region_id: 1

with

region: one

Rails will know that means to set region_id to the id for the region with label one in your fixtures.

like image 144
Frederick Cheung Avatar answered Nov 16 '22 15:11

Frederick Cheung