Activerecord problem

I have the following method…

def index
@posts=Post.find(:all, :include => [:user, :comments])
for post in @posts
puts “Post: #{post.title}”
puts “Written by: #{post.user.title}”
puts “Last comment on: #{post.comments.first.created_at}”
end
end

(the use model)
class User < ActiveRecord::Base
has_many:posts
end

(the post model)

class Post < ActiveRecord::Base
belongs_to:user
has_many :comments, :order => ‘created_at DESC’
end

when i run the application I get the following errors why ? Am i missing
something ???

NoMethodError in TestController#index

You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.title

RAILS_ROOT: D:/InstantRails-2.0-win/rails_apps/active
Application Trace | Framework Trace | Full Trace

app/controllers/test_controller.rb:6:in index' app/controllers/test_controller.rb:4:ineach’
app/controllers/test_controller.rb:4:in `index’

On Aug 7, 2:05 am, Bishal A. [email protected]
wrote:

end

when i run the application I get the following errors why ? Am i missing
something ???

Looks like you’ve got a post without a user. Check what is actually in
the database.

Fred

Frederick C. wrote:

On Aug 7, 2:05�am, Bishal A. [email protected]
wrote:

end

when i run the application I get the following errors why ? Am i missing
something ???

Looks like you’ve got a post without a user. Check what is actually in
the database.

Fred
Thanx for reply…but I have got both tables in tact with foreign key
reference as well…
users table has— id,login,email,title,content and other fields…
posts table has— id,title,content,user_id, …and others… I guess
I have the foreign key reference ok…

Frederick C. wrote:

On Aug 7, 2:05�am, Bishal A. [email protected]
wrote:

end

when i run the application I get the following errors why ? Am i missing
something ???

Looks like you’ve got a post without a user. Check what is actually in
the database.

Fred
Thanx for reply…but I have got both tables in tact with foreign key
reference as well…
users table has— id,title,email,content and other fields…
posts table has— id,title,content,user_id, …and others… I guess
I have the foreign key reference ok…

On Aug 7, 2:38 am, Bishal A. [email protected]
wrote:

the database.

Fred

Thanx for reply…but I have got both tables in tact with foreign key
reference as well…
users table has— id,title,email,content and other fields…
posts table has— id,title,content,user_id, …and others… I guess
I have the foreign key reference ok…

What you’re seeing suggests that your data isn’t quite what you think
it is. Identify the post for which post.user is returning nil and
workout why. unless you’ve got not null on user_id, the foreign key
constraint won’t prevent a null user_id.

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs