简体   繁体   中英

Rails access and save foreign key value inside model

I have two models, Job and Survey . I am using the PaperTrail gem to track changes that occur on the models, and I want to save the job_id onto the version every time it's created.

# 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

When I run this code and try to save a new record, I get the following error:

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

How do I correctly fetch the foreign job_id key from inside my Survey model?

通过使用:job_id而不是self.job_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM