为什么我的外键关联没有产生结果?

时间:2014-06-18 02:18:52

标签: ruby-on-rails ruby-on-rails-3 postgresql

我的rails应用中有两个模型,AppointmentPolicy。我的约会模型has_many :policies, class_name: "Policy", foreign_key: 'writing_code'和我的政策模型belongs_to :appointment。每个表中的writing_code列都是一个字符串。

虽然看起来关联已经完成(我的应用运行),但@appointment.policies没有结果。有人可以解释我在这里出错的地方吗?

此外,为了先发制人地回答这个显而易见的问题,我不能简单地使用appointment_id,因为我将上传与每条记录相关联的约会(或用户)“编写代码”的政策数据。数据将不包括约会ID,因为它来自单独的第三方系统。

提前感谢您的帮助!

编辑:

模式:

create_table "policies", :force => true do |t| 
t.integer "product_id" 
t.decimal "premium" 
t.string "writing_code" 
t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end`

2 个答案:

答案 0 :(得分:1)

我认为这是你的问题:

你有:

class Appointment 
  has_many :policies, class_name: "Policy", foreign_key: 'writing_code'
end

以下是guides says

的内容

“按照惯例,Rails假定用于保存此模型上的外键的列是添加了后缀_id的关联的名称。”

以下是指南中的示例:

class Order < ActiveRecord::Base
 belongs_to :customer, class_name: "Patron",
                    foreign_key: "patron_id"
end

在您的情况下,您的class名称为Policy,但您的foreign_key名称为writing_code。这不是传统的。

答案 1 :(得分:1)

Rails非常自以为是。保持轨道铁路喜欢工作和生活变得更容易。 我同意完全同意@WaliAli说。

“@ appointment.policies不会产生任何结果”

对于具有许多策略的约会,每个策略都需要与模型和表模式中的约会链接。

这意味着策略应该有一个字段'appointment_id',它是一个整数。

将一个appointment_id字段添加到策略表。

$ rails generate migration AddAppointmentIdToPolicies appointment_id:integer
$ rake db:migrate

然后执行以下操作:

class Policy
  has_many :appointments     # this lets you do @policy.appointments
end

class Appointment
  belongs_to :policy         # this lets you do @appointment.policy
end

99%的rails应用程序以另一种方式执行,其中has_many&amp; belongs_to包含更多可选参数,是代码气味。

[更新1:]

  

“我的政策数据将通过.csv从旧系统上传   文件。这些数据不知道的是appointment_id   为什么我需要使用writing_code作为外键值,因为它是   唯一可以关联这两个模型的常见数据。“

我建议将其解析为CSV导入程序的一部分。 导入每条记录时,请查找具有匹配“编写代码”的约会记录,然后保存记录以包含约会ID。

这样的事情:

# Inside your CSV importer script

csv_rows.each do |row|
  policy = Policy.new
  policy.appointment_id = Appointment.find(writing_code: row.writing_code).id
  # more code here..
  policy.save
end