eblume
eblume

Reputation: 1820

Basic Rails design for belongs_to same model

There are many questions like this but I can't find one that seems to answer the specific question - apologies if this is a repeat.

I have a model, let's call it a Shark, with a very simple definition (here, annotated:)

# == Schema Information
#
# Table name: sharks
#
#  id                :integer         not null, primary key
#  created_at        :datetime        not null
#  updated_at        :datetime        not null
#  origination_entry :integer
#

class Shark < ActiveRecord::Base
  belongs_to :originator, class_name: "Shark", foreign_key:"id"
  attr_accessible :origination_entry
end

Specifically, the "origination_entry" column in the database should be a foreign key back to the same table, Sharks. The idea is that every entry might have either null in that relation, or else it will point to another Shark object that was the 'originator' of this Shark. (By 'originator', I am referring to a prior instance of this Shark - trust me, this makes sense with more background.)

Unfortunately this doesn't seem to work.

irb(main):001:0> shark1 = Shark.new(idnumber:"foo")
=> #<Shark id: nil, idnumber: "foo", created_at: nil, updated_at: nil, origination_entry: nil>
irb(main):002:0> shark1.save()
=> true
irb(main):003:0> 
irb(main):004:0* shark2 = Shark.new(idnumber:"foo", origination_entry:shark1.id)=> #<Shark id: nil, idnumber: "foo", created_at: nil, updated_at: nil, origination_entry: 3>
irb(main):005:0> shark2.save()
=> true
irb(main):006:0> shark2
=> #<Shark id: 4, idnumber: "foo", created_at: "2012-06-26 22:35:19", updated_at: "2012-06-26 22:35:19", origination_entry: 3>
irb(main):007:0> shark2.originator
=> nil

(I snipped out some SQL queries, let me know if they would be helpful.)

Why is it returning nil? How can I instead get it to return shark1's object?

Thanks!

Upvotes: 0

Views: 175

Answers (2)

caulfield
caulfield

Reputation: 1373

Try this. It works for me

class Shark < ActiveRecord::Base
   belongs_to :originator, class_name: "Shark", foreign_key:"origination_entry"
   attr_accessible :origination_entry
end

This docs are very useful for AR associations and options ;)

Upvotes: 2

gabrielhilal
gabrielhilal

Reputation: 10769

Try the below:

class Shark < ActiveRecord::Base
  belongs_to : creator, class_name: "Shark", foreign_key:"shark_id"
  attr_accessible :origination_entry
end

Upvotes: 1

Related Questions