Rails:更新后未定义的方法用户名

时间:2015-11-17 22:33:35

标签: ruby-on-rails ruby ruby-on-rails-4

目前正在尝试向我的论坛线程控制器添加编辑功能,但是当我点击更新时,我会得到未定义的方法用户名。

Forum_threads控制器

class ForumThreadsController < ApplicationController
require 'forum_controller'
before_action :authenticate_user!, except: [:index, :show]
before_action :set_forum_thread, except: [:index, :new, :create]

def index
@q = ForumThread.search(params[:q])
@forum_threads = @q.result(distinct: true)
end

def show
@forum_post = ForumPost.new
@forum_posts = @forum_thread.forum_posts.paginate(:page => params[:page], :per_page => 2)
end

def new
@forum_thread = ForumThread.new
@forum_thread.forum_posts.new
end

def create
@forum_thread = current_user.forum_threads.new forum_thread_params
@forum_thread.forum_posts.first.user_id = current_user.id

if @forum_thread.save
  redirect_to @forum_thread
else
  render action: :new
end
end

def edit
end

def update
if @forum_thread.update(forum_thread_params)
redirect_to @forum_thread
else
render 'edit'
end
end

private

def set_forum_thread
  @forum_thread = ForumThread.find(params[:id])
  @forum_post = ForumPost.find(params[:id])
end

def forum_thread_params
  params.require(:forum_thread).permit(:subject, forum_posts_attributes: [:body])
end
end

错误记录

ActionView::Template::Error (undefined method `username' for nil:NilClass):
1:


2: <%= div_for forum_post do %>
3:
Posted by <%= forum_post.user.username %> <%= time_ago_in_words forum_post.created_at %>


4:
<%= forum_post.body %>


5: <% end %>

如果我从HTML中删除了forum_post.user.username,它会加载得很好,我已经尝试将@forum_post添加到更新中,但这也不起作用...

1 个答案:

答案 0 :(得分:0)

您很可能没有提交user_id所以当您使用params调用update时,user_id可能设置为nil。

您可以提前检查在提交更新时是否在param哈希中看到user_id。

您可以在表单上为user_id添加隐藏字段,这应该可以解决问题。

示例:

<%= form_for(@forum_post) do |f| %>
    <%= f.hidden_field :user_id %>
    ...
<% end %>