-1

我正在尝试将数据插入到使用外键关联引用表 A 的表 B 中。
这是我的代码。

模型.rb

class StudentStatusReport < ActiveRecord::Base
attr_accessible :student_id, :mark
belongs_to :student_details, :class_name => "StudentDetails", :foreign_key => "student_id"
end

class StudentDetails < ActiveRecord::Base
attr_accessible :student_id, :name
has_many :student_status_reports
end  

和 Migrations.rb 如下

 class CreateStudentDetails < ActiveRecord::Migration
  def change
  create_table :student_details, {:id => false} do |t|
    t.string :student_id
    t.string :name
    t.timestamps
  end
  execute "ALTER TABLE student_details ADD PRIMARY KEY (reg_no);"
 end
end


class CreateStudentStatusReports < ActiveRecord::Migration
  def change
    create_table :student_status_reports do |t|
     t.string  :student_id
     t.integer :mark
     t.timestamps
   end
 end
end    

现在我使用以下查询将数据插入到 Rails 控制台上的 StudentStatusReport 模型中。

e = StudentDetails.find("UG10001")
f = e.student_status_reports.create!(:mark => 40)

但我在控制台上收到以下错误 -

ActiveRecord::UnknownAttributeError: unknown attribute: student_details_id  

对此可能的解决方案是什么?
我已经在模型和数据库中定义了外键和主键,我不知道我哪里出错了。发送..!

4

1 回答 1

1

我认为问题是你的外键。在StudentStatusReport模型中,您将其定义为表student_id中的列student_status_reports,但在StudentDetails模型中(隐式)定义为student_details_id(Rails 猜测它是关联名称 +_id除非您明确定义它)。因此,应该通过在 parent_model 中指定正确的 foreign_key 来修复错误:

class StudentStatusReport < ActiveRecord::Base
  attr_accessible :student_id, :mark
  belongs_to :student_details, :class_name => "StudentDetails", :foreign_key => "student_id"
end

class StudentDetails < ActiveRecord::Base
  attr_accessible :student_id, :name
  has_many :student_status_reports, :foreign_key => "student_id"
end

请注意,表中的student_idstudent_details实际上并未在关联中使用,因此您可以考虑将其删除以使关联更清晰。

最后,坚持 Rails 中的默认约定通常是一个好主意(整数自动增量主键名为id,单数模型名称)。但有时你就是不能... :S

于 2013-02-15T19:16:18.017 回答