A.R. Associations problem


#1

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


#2

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!


#3

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?

Because you have not set it …

joe = Author.create(:username => “joe”, :email => “jjjj”)
mike = Author.create(:username => “mike”, :email => “mmm”)
topic = joe.topics.create(:topic => “this is a topic”)
post = topic.posts.create(:post => “this is the reply”)
mike.posts << post

Steven Beales

“richard downe” removed_email_address@domain.invalid wrote in
message news:removed_email_address@domain.invalid…