OmomSun
OmomSun

Reputation: 337

Reference another fixture without using label rails

I have this model called Region and Admin

# regions.yml 
one: 
  name: test
two:
  name: test2

# admins.yml 
one:  
  name: admin1
two: 
  name: admin2

There's a column on admin.rb defined as json column (store_accessor: :region_ids). How can I reference regions on admins.yml?

# admins.yml
one: 
  name: admin1
  region_ids: ?????

Upvotes: 4

Views: 1437

Answers (2)

user3366016
user3366016

Reputation: 1312

This is an updated answer using erb to get the id for the various regions.

This creates structure json and queries the database to get the first and second Region IDs. These would be loaded in to the DB from the regions.yml when you run your tests.

# admins.yml
one: 
  name: admin1
  region_ids: >
    [{"region_one_id":<%= Region.first.id.to_json.inspect %>},
    {"region_two_id":<%= Region.second.id.to_json.inspect %>}]

I looked into Fixture label interpolation to get the id but can't figure it out with your table holding json instead of a single id for another model.

Personally I would pre-define your ids on your regions.yml and then directly reference them in your admins.yml. This will help ensure you know the IDs and you have accurate data you've structured to test against.

Upvotes: 2

OmomSun
OmomSun

Reputation: 337

I asked my colleague and got the answer. This will work:

# admins.yml
one: 
  region_ids: <%= Region.pluck(:id) %> 

rails will load regions.yml when it gets to this point.

Upvotes: 2

Related Questions