【问题标题】:Rails 3 : Overriding rails convention to accommodate custom made FK and PKRails 3:覆盖 Rails 约定以适应定制的 FK 和 PK
【发布时间】:2013-02-14 06:41:20
【问题描述】:

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

models.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  

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

【问题讨论】:

    标签: ruby-on-rails-3 activerecord foreign-keys associations has-many


    【解决方案1】:

    我认为问题在于您的外键。在StudentStatusReport 模型中,您将其定义为student_status_reports 表中的student_id 列,但在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_details 表中的student_id 列实际上并未在关联中使用,因此您可以考虑将其删除以使关联更清晰。

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

    【讨论】:

    • 感谢@deivid .. 它工作得很好。你能看看我的其他问题吗plz..stackoverflow.com/questions/14935143/…
    • 我会尽力帮助你,但你显然删除了它......敬礼。
    • 我删除了它,因为这是一个绝对荒谬的问题。我不知道 RoR 已经覆盖了几乎所有的基地......傻我!无论如何谢谢..
    猜你喜欢
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 2011-12-25
    • 1970-01-01
    相关资源
    最近更新 更多