Reputation: 4511
I am new to Active Record. Actually I want to create two models Student and Course where a student have many courses but a course belongs to only one student. I have created model and associated migration as follows:
rails g Student roll_num:string name:string
rails g Course code:string name:string
Model for student should be ideally like that:
class Student < ActiveRecord::Base
has_many :course
end
and that of course should be ideally like that:
class Course < ActiveRecord::Base
belong_to: student
end
My question is such model can be generated with rails g and if so, how? And after creating the model if I specify association then what I have to do so that it gets reflected in the db, I mean foreign key gets created in courses table. Will I have to write separate migration for that?
Upvotes: 0
Views: 94
Reputation: 1040
First change your association in student model
has_many :course
You migration file should include foreign keys
class CreateCourses < ActiveRecord::Migration
def change
create_table :courses do |t|
# your columns
t.references :student
t.timestamps
end
end
end
same See http://sunilsharma3639.wordpress.com/2014/01/10/things-which-rails-could-do-but-i-didnt-know/
Hope it will help you
Upvotes: 0
Reputation: 233
rails g model Student roll_num:string name:string
rails g model Course code:string name:string student:references:index
Also, student has_many :courses
Additional resources: http://edgeguides.rubyonrails.org/migrations.html
Upvotes: 1