[Rails] Re: A.R. Associations problem

richard downe
Fri, 31 Mar 2006 00:52:59 -0000

Sorry, about the incomplete posting above.

Hello,

I''m learning A.R Associations by creating a simple forum that consists
of 3 tables: ahuthors, topics and posts.

This is the schema:
  class AddAuthorAndTopicAndPostTables < ActiveRecord::Migration
  def self.up
    create_table :authors do |t|
      t.column :username, :string
      t.column :email, :string
      t.column :created_on, :datetime
    end

    create_table :topics do |t|
      t.column :topic, :string
      t.column :author_id, :integer
      t.column :created_on, :datetime
    end

    create_table :posts do |t|
      t.column :post, :text
      t.column :topic_id, :integer
      t.column :author_id, :integer
      t.column :created_on, :datetime
    end
  end

  def self.down
    drop_table :authors
    drop_table :topics
    drop_table :posts
  end
end

Here are the model associations:
class Author < ActiveRecord::Base
  has_many :topics
  has_many :posts
end

class Topic < ActiveRecord::Base
  has_many :posts
  belongs_to :author
end

class Post < ActiveRecord::Base
  belongs_to :topic
  belongs_to :author
end

At the console, I am able to save to all 3 tables.  For example ...
joe = Author.create(:username => "joe", :email =>
"jjjj")
topic = joe.topics.create(:topic => "this is a topic")
 topic.posts.create(:post => "this is the reply")

The problem lies in topic.posts object which shows the hash value of
"author_id" to be nil.  Why doesn''t this object also contain
the
author_id?

Thanks in advance for any assistance!



--
Posted via http://www.ruby-forum.com/.