简体   繁体   中英

Creating association in rails active record

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM