我有一个包含多个帖子的主题。每个 Post 属于一个 User,每个 User 都有一个 Profile。
在特定主题的“显示”页面中,我尝试显示创建帖子的用户的个人资料信息:
<% @topic.posts.each do |post| %>
<%= post.user.profile.first_name %>
<% end %>
我收到以下错误:
nil:NilClass 的未定义方法“profile”
知道为什么它不允许我访问个人资料吗?请指教。
我的主题控制器如下:
class TopicsController < ApplicationController
# GET /topics
# GET /topics.json
add_breadcrumb :index, :topics_path
def index
if params[:tag]
@topics = Topic.tagged_with(params[:tag])
else
@topics = Topic.all
end
@newtopic = Topic.new
respond_to do |format|
format.html # index.html.erb
format.json { render json: @topics }
end
end
# GET /topics/1
# GET /topics/1.json
def show
@topic = Topic.find(params[:id])
@posts = @topic.posts
@newpost = @topic.posts.build
add_breadcrumb @topic.name
respond_to do |format|
format.html # show.html.erb
format.json { render json: @topic }
end
end
# GET /topics/new
# GET /topics/new.json
def new
add_breadcrumb :new, :topics_path
@topic = Topic.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @topic }
end
end
# GET /topics/1/edit
def edit
@topic = Topic.find(params[:id])
end
# POST /topics
# POST /topics.json
def create
@topic = Topic.new(params[:topic])
@topic.user_id = current_user.id
@topic.last_poster_id = current_user.id
@topic.last_post_at = Time.now
respond_to do |format|
if @topic.save
format.html { redirect_to @topic, notice: 'Topic was successfully created.' }
format.json { render json: @topic, status: :created, location: @topic }
else
format.html { render action: "new" }
format.json { render json: @topic.errors, status: :unprocessable_entity }
end
end
end
# PUT /topics/1
# PUT /topics/1.json
def update
@topic = Topic.find(params[:id])
respond_to do |format|
if @topic.update_attributes(params[:topic])
format.html { redirect_to @topic, notice: 'Topic was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @topic.errors, status: :unprocessable_entity }
end
end
end
# DELETE /topics/1
# DELETE /topics/1.json
def destroy
@topic = Topic.find(params[:id])
@topic.destroy
respond_to do |format|
format.html { redirect_to topics_url }
format.json { head :no_content }
end
end
end