AR模型关系的未定义方法创建

时间:2015-10-27 04:06:32

标签: ruby-on-rails activerecord

我的Rails应用程序中有两个模型:

class Student < ActiveRecord::Base
  belongs_to :higher_education
  attr_accessible :higher_education_id
end

class HigherEducation < ActiveRecord::Base
  has_many :students
end

首先,我执行以下命令:

he = HigherEducation.create()

 (0.0ms)  begin transaction                                                                                                                    
  SQL (56.4ms)  INSERT INTO "higher_education" ("created_at", "text", "updated_at") VALUES (?, ?, ?)  [["created_at", Tue, 27 Oct 2015 04:22:14 UTC +00:0│
0], ["text", "baz"], ["updated_at", Tue, 27 Oct 2015 04:22:14 UTC +00:00]]                                                                       │
   (10.3ms)  commit transaction                                                                                                                 
=> #<HigherEducation id: 3, text: "baz", created_at: "2015-10-27 04:22:14", updated_at: "2015-10-27 04:22:14">

接下来,我执行另一个命令并收到错误:

he.students.create()
=> nil

我回来了NoMethodError: undefined method create for nil:NilClass

知道问题是什么吗?

1 个答案:

答案 0 :(得分:0)

删除attr_accessible :higher_education_id

Rails在启动时读取数据库模式(不是schema.rb,而是实际的表),并为数据库中的列创建setter和getter。

假设您的表格如下:

students
  - id [Int, Index, primary key]
  - email [Varchar]
  - higher_education_id [Int, Index, Foreign Key]

您的学生实例已经回复.email.email=.higher_education_id.higher_education_id= ...

此外,当您在模型中设置关系时,Rails将覆盖这些setter和getter,以便他们也设置相关对象。

在ActiveRecord模型中唯一应该使用attr_accessible的是当您想要使用不受数据库列支持的“虚拟属性”时。