0

I have two database tables being domains and categories.

Domains can have many categories and categories can have many domains.

Both models are setup using has_and_belongs_to_many.

Logically when a category is associated with a domain conversely a domain is associated with a category. However...

irb(main):062:0> domain.categories.any?
=> false
irb(main):063:0> category.domains.any?
=> true

What am I missing?

Dercni
  • 1,216
  • 3
  • 18
  • 38

1 Answers1

2

HABTM

For posterity, you'll need to have the following set up:

#app/models/domain.rb
class Domain < ActiveRecord::Base
   has_and_belongs_to_many :categories
end

#app/models/category.rb
class Category < ActiveRecord::Base
   has_and_belongs_to_many :domains
end

#table - categories_domains - category_id | domain_id

This gives you the relative associations you require to call the domain.categories or category.domains methods on your respective objects.


Associations

To underline this idea for you (as you're new), let me detail the importance of ActiveRecord associations in Rails.

Rails is an MVC framework, and is object orientated. This won't mean much if you're starting, but as you progress, it will become very important.

The object orientated nature of Rails means that each time you want to add a piece of functionality, you really need to work around objects. Your objects, as per the MVC convention, are build inside the Model (which is why you can call Model.new etc)

When you associate objects (models), you basically tell Rails (through ActiveRecord), that the two objects are associated. AR is what's known as an ORM - object relationship mapper - which means it provides an abstraction layer to allow you to call associative data more easily:

enter image description here

--

This means that if you want to associate two objects (models) together, you basically need to define the two associations in your respective models, which will then provide the functionality in the other parts of your app

Richard Peck
  • 76,116
  • 9
  • 93
  • 147