Reputation: 2494
I'm trying to map in Sinatra with ActiveRecord my MySQL dB. The db doesn't follow the ActiveRecord convention, so I need to map everything adding attributes to my Classes.
Everything is ok with one to many and one to one association, but I have problems with m to m.
I have an article table named "Eve_Articles"
I have a product tablet named "Eve_product"
I have a join table named "Eve_Articles_Product" where tree_id is the article ID and prod_id is the Product ID.
I create the models:
class Article < ActiveRecord::Base
self.inheritance_column = :_type_disabled
has_one :image, class_name: 'Image', foreign_key: 'tree_id'
has_and_belongs_to_many :products,
end
class Product< ActiveRecord::Base
self.inheritance_column = :_type_disabled
has_and_belongs_to_many :articles,
end
But I don't know how to define the custom join table with custom keys.
Upvotes: 0
Views: 618
Reputation: 29349
Use join_table
option. Also you will have to set the table_name
for Article
and Product
since its not following the rails convention
You will have to set the table name after the habtm call according to this line from documentation.
WARNING: If you’re overwriting the table name of either class, the table_name method MUST be declared underneath any has_and_belongs_to_many declaration in order to work.
class Article < ActiveRecord::Base
self.inheritance_column = :_type_disabled
has_one :image, class_name: 'Image', foreign_key: 'tree_id'
has_and_belongs_to_many :products, :join_table => "Eve_Articles_Product", :association_foreign_key => 'tree_id', :foreign_key => 'prod_id'
self.table_name = "Eve_Products"
end
class Product< ActiveRecord::Base
self.inheritance_column = :_type_disabled
has_and_belongs_to_many :articles, :join_table => "Eve_Articles_Product", :association_foreign_key => "prod_id", :foreign_key => 'tree_id'
self.table_name = "Eve_Articles"
end
Upvotes: 1