Rails访问并保存模型中的外键值

时间:2015-06-21 08:41:26

标签: ruby-on-rails rails-activerecord rails-models

我有两个模型,JobSurvey。我正在使用PaperTrail gem来跟踪模型上发生的变化,我想在每次创建时将job_id保存到版本中。

# app/models/job.rb

class Job < ActiveRecord::Base

  has_paper_trail :ignore => [:id, :created_at, :updated_at],
                  :meta => { :resource_id => self.id }

  has_one :survey

end

# app/models/survey.rb

class Survey < ActiveRecord::Base

  has_paper_trail :ignore => [:id, :created_at, :updated_at],
                  :meta => { :resource_id => self.job_id }

  belongs_to :job

end

# app/db/schema.db

# versions
create_table "versions", force: :cascade do |t|
  t.string   "item_type",      null: false
  t.integer  "item_id",        null: false
  t.string   "event",          null: false
  t.string   "whodunnit"
  t.text     "object"
  t.datetime "created_at"
  t.text     "object_changes"
  t.integer  "resource_id"
end

# surveys
create_table "surveys", force: :cascade do |t|
  t.string   "survey"
  t.integer  "job_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

当我运行此代码并尝试保存新记录时,出现以下错误:

undefined method `job_id' for #<Class:0x007fd53d70c0a0>

如何从job_id模型中正确获取外部Survey密钥?

1 个答案:

答案 0 :(得分:0)

使用planetAnimation.Sprite.Name = "Sprites\\Planets\\mars";代替:job_id解决。