Rails has_and_belongs_to_many confuse me with appliances and factories

General confusion
I have groups that can have 3 genres. I read in a previous SO post that the right way to handle this is a few steps:

1) In band.rb

has_and_belongs_to_many :genres 

2) Create a band_genres join table

Even after reading the documentation, I'm a little confused about what HABTM actually means. Probably, I would just think: "The group has many genres," it does not and belongs to many. So a quick DUMBED explanation of this would be wonderful.

Confusion with lights

Also, when executing my tool for band_genres, I have

 { "The Reaper Band and Funk": { "band": "The Reaper Band", "genre": "Funk" }, "The Reaper Band and Rock": { "band": "The Reaper Band", "genre": "Rock" } } 

And I get the "unknown" column. I thought that the rails should have known that the "The Reaper Band" would refer to a group from the ensemble (same name) and grab this identifier and find out that the "group" in this tool would refer to band_id in the connection table, I preferred so that my lights look as if they were hardcoded.

Confusion with plants

When I create a group in my factory, I want to assign it to genres:

 Factory.define :band do |f| f.sequence(:name) { |n| "Band#{n}" } f.mailing_lists { |mailing_lists| [mailing_lists.association(:mailing_list)] } f.genres 2 end 

I understand that I will probably need a hard genre_id code. But why the rails do not look at it and say: "Oh, he wants to add a genre with id = 2 to the band_genres table."

I don't expect the rails to take care of my dirty work for me, but I want to play by the rules.

+6
ruby-on-rails has-and-belongs-to-many fixtures factories
source share
1 answer
  • It has and belongs to many, defines relations in both directions. If you only need to see which genres the group belongs to, has_many will be fine. If you want to know which groups are "funk", you can use HABTM to allow the search for groups for a particular genre.
  • For luminaires in rails, you can now make HABTM without creating a separate luminaire for the connection table. For example:

in .yml bands:

 reaper_band: name: The Reaper Band genres: funk, rock 

in .yml genres:

 funk: name: Funk bands: reaper_band rock: name: Rock bands: reaper_band 
+21
source share

All Articles