如何使用Rails控制台定义has_one / belongs_to之间的关系

时间:2015-07-30 00:34:52

标签: ruby-on-rails-4 polymorphism

您好我希望能够在Rails控制台中定义has_one / belongs_to关系。我正在使用Rails 4(如果这很重要)。在阅读了其他一些主题之后,我尝试了一些方法,但这里首先是我的模型。

class Appointment < ActiveRecord::Base
    belongs_to :patient
end

class Patient < ActiveRecord::Base
    has_one :appointments
end

我已经看到可能需要创建一个attr_accessor,但我的教师能够在任何一个类中都没有它,并且如果可能的话我想模仿它。我试过了:

a = Appointment.create(date: "9/9/15", patient_id: 2)

=> ActiveRecord::UnknownAttributeError: unknown attribute 'patient_id' for Appointment.

a.patient = s  //after defining both (s being patient)
 => ActiveModel::MissingAttributeError: can't write unknown attribute `patient_id`

以及其他一些方法,但我会免费给你所有的复制粘贴。我该怎么做?

1 个答案:

答案 0 :(得分:0)

该错误表示您尚未在appointments表中定义名为{{1}}的列。

您需要通过migration引入此列,而不是通过Rails控制台。 Rails控制台是一个REPL环境,可以访问您的模型层,它与您要实现的目标无关。