Rails - How to use the has_and_belongs_to_many association with compound primary keys

I am using Dr.Nic Composite Primary Keys for rails (http://compositekeys.rubyforge.org/)

In the examples, it has has_many and belongs to a relation, but not has_and_belongs_to_many

My association works well with books in genres (books contain complex title and author body text), but the genre in books tries to query for the column book_id, which is not in the connection table, and causes an error.

class Book < ActiveRecord::Base self.primary_keys = :title, :author has_and_belongs_to_many :genres, foreign_key: [:title, :author] end class Genre < ActiveRecord::Base has_and_belongs_to_many :books, foreign_key: [:title, :author] end 

Edit: I also got it to work using the :association_foreign_key option in the Genre model

 class Genre < ActiveRecord::Base has_and_belongs_to_many :books, association_foreign_key: [:title, :author] end 
+8
ruby-on-rails
source share
1 answer

According to the Ruby on Rails Style Guide :

Prefers has_many: through has_and_belongs_to_many. Using has_many: through allows additional attributes and checks in the connection model.

This will solve your problem: you should only have has_many and belong to the relationship, no HABTM;)

In your case:

 class Book < ActiveRecord::Base self.primary_keys = :title, :author has_many :book_genre_relations has_many :genres, through: :book_genre_relations end class Genre < ActiveRecord::Base has_many :book_genre_relations has_many :books, through: :book_genre_relations end class BookGenreRelation < ActiveRecord::Base # Sorry but couldn't find a better name... belongs_to :book belongs_to :genre end 

You may have to change the typo for foreign_key, I am not familiar with compound primary keys.

+7
source share

All Articles