ruby-on-railsrubyfixtures

Rails fixtures :has_many and :belongs_to


How do I create sample data in my .yml for has_many and belongs_to variables.

This is a sample adding these files into a simple rails new lab command in the terminal. I don't really know how to explain this in english. But I hope my code shows enough detail to get the point across.

man.rb

class Man < ActiveRecord::Base
  attr_accessible :name
  has_many :items
end

item.rb

class Item < ActiveRecord::Base
  attr_accessible :name
  belongs_to :man
end

men.yml

one:
  name: ManOne
  #items: one, two

two:
  name: ManTwo
  #items: one, two

items.yml

one:
  name: ItemOne

two:
  name: ItemTwo

man_test.rb

require 'test_helper'

class ManTest < ActiveSupport::TestCase
  def test_man
    Man.all.each do |man|
      puts man.name.to_s + ": " + man.items.to_s
    end
    assert true
  end
end

Solution

  • Have a look to fixtures docs, you can do something like:

    men.yml

    man_one:
      name: ManOne
    
    man_two:
      name: ManTwo
    

    items.yml

    item_one:
      name: ItemOne
      man: man_one
    
    item_two:
      name: ItemTwo
      man: man_one
    
    item_three:
      name: ItemThree
      man: man_two
    

    Update

    It seems you don't have the man_id in the table column. You should create a migration to do so:

    rails g migration AddManIdToItem man_id:integer
    

    and run the migration: bundle exec rake db:migrate