0

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?

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.