【问题标题】:implementing Active Record Guide 2.4 The has_many :through Association实现 Active Record Guide 2.4 has_many :through 关联
【发布时间】:2014-08-07 18:37:20
【问题描述】:

我正在尝试实现http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association中的示例

但我不确定正确的方法是什么?您是否先创建迁移,然后通过更改模型在模型中应用 has many through?

hospital$ rails g model Physician name:string
      invoke  active_record
      create    db/migrate/20140807183053_create_physicians.rb
      create    app/models/physician.rb
      invoke    test_unit
      create      test/models/physician_test.rb
      create      test/fixtures/physicians.yml
hospital$ rails g model Patient name:string
      invoke  active_record
      create    db/migrate/20140807183112_create_patients.rb
      create    app/models/patient.rb
      invoke    test_unit
hospital$ rails g model Appointment physician:references patient:references appointment_date:datetime
      invoke  active_record
      create    db/migrate/20140807183152_create_appointments.rb
      create    app/models/appointment.rb
      invoke    test_unit
      create      test/models/appointment_test.rb
      create      test/fixtures/appointments.yml

这些是生成的模型:

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
end

class Physician < ActiveRecord::Base
end

是否有关于实施 has many through 模型的分步指南?该指南解释了这个想法,我理解它,但我不确定实际实施它的正确方法,或者它是否重要?我很困惑

【问题讨论】:

    标签: activerecord ruby-on-rails-4


    【解决方案1】:

    好吧,您编写迁移或应用代码的顺序并不重要。但是只有在您使用rake db:migrate运行迁移后,您的代码才会起作用。

    在您发布的代码中,您显然缺少 has_many 方法。也许你喜欢this quick tip 了解什么是以及如何通过关联构建 has_many

    编辑:

    您绝对可以手动将 has_many 放入其中。生成器使它更容易。但是,如果您感到困惑,我建议您手动编写代码并在之后运行迁移。

    【讨论】:

    • 所以我在模型中手动添加了has many through?我只是感到困惑,因为我认为我应该只通过迁移来完成
    • 谢谢,我认为一切都必须通过迁移来完成!!
    • 你个人会怎么做?对所有内容进行迁移?
    • 我通过生成器生成模型。然后我运行它。然后我在模型中添加额外的方法,无论缺少什么东西......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    相关资源
    最近更新 更多