I've got a model that is analogous to the Categories
model discussed in this previous discussion of many-to-many relationships. Briefly, I have many stock categories (~200 categories) that I want to be loaded for all users. I want the has_and_belongs_to_many relationship
so I can easily find those users that have the various categories and count the number of users with each category. If a user deletes their use of a category, I need it to be available for others, even if no one is using it.
I've gotten it to work in the console and in development mode, but it doesn't seem to be working in test mode, which makes me think there must be a better way of doing this.
In db/seeds.rb
, I have an array...
c = [ "Category 1", "Category 2", "Category 3", "Category 4" ]
c.each { |cat| Category.create!(category: cat)}
I know that there is a problem in test mode because if I include...
$stdout.print Category.first.category
in a test, I get...
Error:
CategoryTest#test_should_be_valid:
NoMethodError: undefined method `category' for nil:NilClass
test/models/category_test.rb:17:in `block in <class:CategoryTest>'
Alternatively, if I do...
Category.create!(category: "Category 5")
$stdout.print Category.first.category
It outputs Category 5
.
Any ideas on a better way of initializing Category
objects and how I can get it to be seen in test mode?