2016-10-03 75 views
0

我有两个名为Post和PostComment的模型。 目前,我用hidden_field形式助手发送额外的数据,如后一次,评论海报和后ID上的评论正在取得这样的用户ID:Rails将额外参数传递给请求而不使用hidden_​​field标记

<%= f.hidden_field :posttime, value: Time.now.getutc %> 
<%= f.hidden_field :post_id, value: @post.id %> 
<%= f.hidden_field :user_id, value: current_user.id %> 

点击它晚了,我认为我可以使用浏览器的检查员更改这些值,因此这是安全漏洞。那么如何安全地发送这些参数?

回答

1

通常这些值不是通过表单传递,而是通过使用嵌套的URL网址进行访问(读取怎么会在这里:http://guides.rubyonrails.org/routing.html

例如使用post_id形式的网址,你会设定您的评论路线包括帖子,例如,您将拥有new_post_comment_path,并且在您的控制器中,您可以访问params[:post_id]而不通过表单。

你的形式将成为这样的事情:

<% form_for [@post, Comment.new] do |f| %> 
    ... 

重:user_id - 绝对不传递的形式,你说的很对,这是一个很大的安全隐患(人们可以添加评论对于其他人!)只需通过您的控制器中的身份验证方法(即current_user)访问它。

你会最终在你的控制器例如是这样的:

def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.new(comment_params) 
    @comment.user = current_user 
    if @comment.save 
    redirect_to [@post, @comment] 
    else 
    render_action :new 
    end 
end 

private 

# Don't forget to use require/permit to make sure the user can't 
# fake up the user/post id fields themselves out of whole-cloth 
def comment_params 
    # or whatever your permitted comment-fields are. 
    params.require(:comment).permit(:content) 
end 
+0

感谢许多清算事情为我。我不知道'post_id'参数会自动传递,现在它更有意义。由于我使用的是设计,不应该是'@post_comment.user_id = current_user.id'(这意味着你的代码行是错误的或者至少不遵循约定) –

+0

只要你有一个'belongs_to:user '在'Comment'模型中,你可以使用'user'或'user_id',他们都会正常工作:) 如果你有一个或者另一个验证 - 使用带验证的验证...(例如'validates_presence_of:user_id'意味着你应该更喜欢'@comment.user_id = current_user.id') –

+0

太好了!由于我们在控制器本身的用户标识中进行了归档,并且我确定该表单仅在用户登录时才可见,因此不需要“validates_presence_of:user_id”权限? –

1

Time.now.getutccurrent_user.id已经可以在你的createupdate方法的应用,所以你并不真的需要通过那些回来。至于@post.id你可以只存储在您的newedit方法会话变量...

session[post_id] = @post.id 

,然后在你的create或`更新方法...

@post_comment.post_id = session[:post_id] 
+0

我完全没有想到'Time.now.utc'可以在控制器内部使用。感谢您发现它。 –

相关问题