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
Not sure this will make a difference, but have you tried separating the belongs_to associations?
belongs_to :photo
belongs_to :user
+1 for using haml
i can think of a few reasons why this might happen
firstly, what happens when your remove the following line from your code?
# try removing this
%p=comment.user.fname
Does the error then move on to next variable (i.e. comment.body)
If not, then you have at least narrowed it down to the fname variable. in which case I would wonder if you have perhaps added the fname variable to your model after creating some intitial database entries... this would mean that some of hte entries don't have associated fname variables. in this instance you can fix the issue by scrubbing the database and remigrating from scratch
Also, do you have attr_accessible set for the fname variable in your model? chekc that you have this set for all the variables.
can you look inside your db and make sure that all entries have an fname variable set?
I realise that you want to get this working but if you can't, there's no shame in using the disqus.com plugin - it saves you db space, helps to attract more comments as lots of people already have profiles and gives you some nifty moderator features... on the downside, you lose branding, and you can't use any of your own rjs effects..
good luck
精彩评论