显示创建帖子和评论的用户的用户名的有效方法是什么?

时间:2014-10-26 01:55:12

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

现在我的帖子有user_id

def create

@post = @user.posts.new(post_params)


@post.user_id = current_user.id

if @post.save
  redirect_to @post
else
  render :new
end
end

我在展会视图中链接到用户的用户名:

<%= @user.username %>

显示操作:

def show
@post = Post.find(params[:id])
@user = User.find(@post.user_id)
end

当我访问我的节目视图时,没有显示任何内容,但我没有收到错误消息。

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

我认为更好的方法是通过帖子向用户显示:

<%= @post.user.username %>

这很简单,毫无疑问我会显示帖子的用户,而不是current_user或其他任何用户。

要显示这种方式,您必须执行一些急切的加载以防止重复的数据库调用:

def show
  @post = Post.includes(:user).find(params[:id])
end

您必须避免这种情况:params.require(:post).permit(:user_id),这是一个安全问题。为什么?因为您只能在期望用户发送的params上调用permit。然后假设current_user返回记录的用户:

def create
  @post = Posts.new(post_params)
  @post.user_id = current_user.id
  if @post.save
    redirect_to @post
  else
    render :new
  end
end

def post_params
  params.require(:post).permit(:only_post_data_that_user_send)
end

我认为必须这样做。如果不起作用,请确保current_user必须是用户登录,之后认为post.user_id可以为nil,如果不是从db中删除不良记录,则向Post添加验证。如果它可以是零使用:@post.user.try(:username)

相关问题