Hi,
It's driving me crazy. I have 3 models. User, Photo, Comments.
Here is what I want to do.
A user has many photos and comments
A photo belongs to a user and has many comments
And a comment belongs to user and to a photo
So my models have these associations:
User
has_many :photos, :dependent => :destroy
has_many :comments, :dependent => :destroy
Photo
belongs_to :user
has_many :users, :through => :comments
has_many :comments, :dependent => :destroy
Comment
belongs_to :photo, :user
I want now to show a photo and load all the comments of this photo and display each comment with the user info.
So at the photos controller show action I have
@photo = Photo.find(params[:id], :include => :comments, :order => 'comments.created_at DESC')
And in the photo/show view
=render :partial => "/comments/partials/comment", :collection => @photo.comments, :as => :comment
It display the comments eg. the comment text fine but when inside the partial I try to do:
%p=comment.user.fname
%p=comment.body
It throws error "undefined method `fname' for nil:NilClass"
Something strange is that I am user authlogic so you have to be logged in to post a comment. But you can see the comments even if you are not logged in. When I am logged off it works find. When I log in it throws error.
Any help would be much appreciated cause it is driving me nuts.
By the way in my routes I have
map.resources :users, :has_many => [:photos, :comments]
map.resources :photos, :has_many => [:comments, :users]
Thanks