【问题标题】:Creating association in rails active record在 Rails 活动记录中创建关联
【发布时间】:2014-02-11 03:34:10
【问题描述】:

我是 Active Record 的新手。实际上我想创建两个模型学生和课程,其中一个学生有很多课程,但一门课程只属于一个学生。我创建了模型和相关的迁移如下:

rails g Student roll_num:string name:string
rails g Course code:string name:string

学生模型最好是这样的:

class Student < ActiveRecord::Base
   has_many :course
end

当然理想情况下应该是这样的:

class Course < ActiveRecord::Base
   belong_to: student
end 

我的问题是这样的模型可以用 rails g 生成,如果可以,如何生成?在创建模型之后,如果我指定关联,那么我必须做什么才能反映在数据库中,我的意思是在课程表中创建外键。我需要为此编写单独的迁移吗?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:
    rails g model Student roll_num:string name:string
    
    rails g model Course code:string name:string student:references:index
    

    另外,学生 has_many :courses

    其他资源:http://edgeguides.rubyonrails.org/migrations.html

    【讨论】:

      【解决方案2】:

      首先在学生模型中更改您的关联

      has_many :course
      

      你的迁移文件应该包含外键

      class CreateCourses < ActiveRecord::Migration
        def change
          create_table :courses do |t|
            # your columns
            t.references :student
      
            t.timestamps
          end
        end
      end
      

      相同 见http://sunilsharma3639.wordpress.com/2014/01/10/things-which-rails-could-do-but-i-didnt-know/

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-23
        • 1970-01-01
        • 1970-01-01
        • 2015-02-27
        相关资源
        最近更新 更多