I am currently building very simple Comment system on Rails. The primary models are User, Albumpost, and Comment. Users can post Albumposts. For each Albumpost, Users can add Comments to the Albumpost. As a result, a Comment belongs to a User and belongs to an Albumpost.
The problem I’m having is that even with the proper associations in my models (see below), I can’t get
@comment.user.name
when I’m trying to render the comments in the albumpost ‘show’ page (/views/albumposts/show.html.erb). When I go to the page, I can’t get @comment.user.name (doesn’t understand the association) and get a
"undefined method `name' for nil:NilClass"
Oddly I can get
@comment.albumpost.content
I’ve double-checked my models and also added the proper foreign keys to the models. Am I doing something wrong in the controllers?
Here are my models:
class Comment < ActiveRecord::Base
attr_accessible :body, :albumpost_id, :user_id
belongs_to :albumpost
belongs_to :user
end
class Albumpost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
has_many :comments, dependent: :destroy
end
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_many :albumposts, dependent: :destroy
has_many :comments, dependent: :destroy
end
Here are the relevant parts of my Albumpost and Comments controllers:
class AlbumpostsController < ApplicationController
def show
@albumpost = Albumpost.find(params[:id])
@comments = @albumpost.comments
@comment = Comment.new
@comment.albumpost_id = @albumpost.id
@comment.user_id = current_user.id
end
end
class CommentsController < ApplicationController
def create
albumpost_id = params[:comment].delete(:albumpost_id)
@comment = Comment.new(params[:comment])
@comment.albumpost_id = albumpost_id
@comment.user_id = current_user.id
@comment.save
redirect_to albumpost_path(@comment.albumpost)
end
end
I think you should prefer setting objects to relations instead of setting their ids. For example, you should do this:
instead of
ActiveRecord will take care of setting corresponding
*_idfields. I’m not sure how it handles the reverse. (it should autoload though, if I understand correctly)