3

Product,Category is two model on rails3 the relation between them are follow:

product has_and_belongs_to_many categories

category has_and_belongs_to_many products

i can use scaffold generate migration for this two modle use

rails g scaffold product name:string
rails g scaffold category name:string

but how can i generate the many to many model's middle table migration info,or i need write it manually,if so this is hard for me,hope someone could help me.

mlzboy
  • 14,343
  • 23
  • 76
  • 97
  • http://guides.rubyonrails.org/association_basics.html#tips-tricks-and-warnings i foud some useful link,it seems need create the assocation table by myself,if so rails is not such magic in my mind – mlzboy Oct 30 '10 at 03:33
  • http://en.wikibooks.org/wiki/Ruby_on_Rails/ActiveRecord/Associations#has_and_belongs_to_many also i found another relevent link,i have another question is how to named assocation table,products_categories or categories_products,if both two model start with c or p character put which model name first in assocation-table name – mlzboy Oct 30 '10 at 03:42

2 Answers2

2
rails g model ProductCategories product:references category:references
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188
2

You need create this table by yourself

   create_table :products_categories, :id => false do |t| 
     t.integer :product_id 
     t.integer :category_id
   end

Warning, you need define the :id to false, because this table no need id column. If you have an id column, the table is invalid to be used on has_and_belongs_to_many .

shingara
  • 46,608
  • 11
  • 99
  • 105