使用db:seed设置外键值

时间:2014-03-27 20:57:28

标签: ruby-on-rails activerecord seed

我是rails n00b并尝试为我的rails原型创建一个种子文件。这是我的模特:

class Planning::Visit < ActiveRecord::Base
  has_many :planning_tasks, class_name: "Planning::Task"
end

class Planning::Task < ActiveRecord::Base
  belongs_to :planning_visits, class_name: "Planning::Visit"
end

我正在用20个条目播种我的访问,这没有问题。我想用几个条目来分配任务,这些条目对每个条目分配了随机访问。我已经尝试了以下各项而没有运气:

FAIL

task_list.each do |name, title, description, ship, hours|
  @task = Planning::Task.create( name: name, title: title, description: description, ship: ship, manhours: manhours ) # Create the base task
  @visit = Planning::Visit.find(:all, select: 'id', order: 'RANDOM()', limit: 1)  # Find a random visit
  @task.planning_visit_id = @visit.id  # Assign the random visit to the Task
  @task.save # Save the task
end

FAIL

task_list.each do |name, title, description, ship, hours|
  Planning::Task.create( name: name, title: title, description: description, ship: ship, manhours: manhours, planning_visit_id: Planning::Visit.find(:all, select: 'id', order: 'RANDOM()', limit: 1) )
end

任务创建但没有为其分配planning_visit_id。

我的架构定义为:

create_table "planning_visits", force: true do |t|
  t.integer  "visit_number"
  t.date     "start_date"
  t.date     "end_date"
  t.string   "station"
  t.string   "ship"
  t.string   "priority"
  t.text     "notes"
  t.boolean  "lock_date"
  t.boolean  "lock_station"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.boolean  "has_issue"
  t.string   "issue_severity"
end

create_table "planning_tasks", force: true do |t|
  t.string   "name"
  t.string   "title"
  t.string   "description"
  t.string   "ship"
  t.integer  "manhours"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "planning_visit_id"
end

我真的很感激这里的一些帮助,因为我的头发已经用完了,还有墙壁可以穿孔。

1 个答案:

答案 0 :(得分:1)

belongsTo是单数:planning_visit

检查documentation for belongsTo relation