I have the following 3 classes:
class User < ActiveRecord::Base
has_many(:project_roots)
end
class Project < ActiveRecord::Base
self.acts_as_tree(:order => “title”, :uniq=>true)
def user()
self.root.user()
end
end
class ProjectRoot < Project
self.belongs_to(:user)
def user()
read_attribute(:user)
end
end
and these 2 migrations:
class CreateProjects < ActiveRecord::Migration
def self.up
create_table :projects do |t|
t.column :type, :string # single-table inheritance
# common attributes
t.column :parent_id, :integer
t.column :title, :string
t.column :description, :text
# attributes for type=ProjectRoot
t.column :user_id, :integer
end
end
end
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.column :name, :string
t.column :password_code, :string
t.column :password_salt, :string
end
end
end
First I uncomment out ProjectRoot#user, and then do this in a console:
u1=User.find_first
p1=ProjectRoot.new(:title=>‘p1’, :description=>‘p1’)
u1.project_roots<<p1
p1.user
=> nil
I put the comments back in (and bring up a new console, and again run
the above) and now correctly get this:
p1.user
=> #<User:0x4807bdc …>
- Why is read_attribute not working?
Furthermore, (with the comments left in) I proceed to do:
p2=Project.new(:title=>‘p2’, :description=>‘p2’)
p1.children<<p2
p2.root
=> #<ProjectRoot:0x47f4ed8 @attributes={“title”=>“p1”, …>p2.user
=> #<User:0x47f1f94 …>
- Why don’t I get into an infinite loop with Project#user? (Actually
this consideration was the very reason for implementing
ProjectRoot#user.)
All help greatly appreciated.