Rails 3 has_and_belongs_to_many migration -


i have 2 models restaurant , user want perform has_and_belongs_to_many relationship.

i have gone model files , added has_and_belongs_to_many :restaurants , has_and_belongs_to_many :users

i assume @ point should able rails 3:

rails generate migration .... 

but have tried seems fail. i'm sure simple i'm new rails i'm still learning.

you need add separate join table restaurant_id , user_id (no primary key), in alphabetical order.

first run migrations, edit generated migration file.

rails 3

rails g migration create_restaurants_users_table 

rails 4:

rails g migration create_restaurants_users 

rails 5

rails g migration createjointablerestaurantuser restaurants users 

from docs:

there generator produce join tables if jointable part of name:


your migration file (note :id => false; it's prevents creation of primary key):

rails 3

class createrestaurantsusers < activerecord::migration   def self.up     create_table :restaurants_users, :id => false |t|         t.references :restaurant         t.references :user     end     add_index :restaurants_users, [:restaurant_id, :user_id]     add_index :restaurants_users, :user_id   end    def self.down     drop_table :restaurants_users   end end 

rails 4

class createrestaurantsusers < activerecord::migration   def change     create_table :restaurants_users, id: false |t|       t.belongs_to :restaurant       t.belongs_to :user     end   end end 

t.belongs_to automatically create necessary indices. def change auto detect forward or rollback migration, no need up/down.

rails 5

create_join_table :restaurants, :users |t|   t.index [:restaurant_id, :user_id] end 

note: there option custom table name can passed parameter create_join_table called table_name. docs

by default, name of join table comes union of first 2 arguments provided create_join_table, in alphabetical order. customize name of table, provide :table_name option:


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -