Rails将额外参数传递给请求而不使用hidden_field标记
我有两个名为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 %>
点击它晚了,我认为我可以使用浏览器的检查员更改这些值,因此这是安全漏洞。那么如何安全地发送这些参数?
通常这些值不是通过表单传递,而是通过使用嵌套的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
的Time.now.getutc
和current_user.id
已经可以在你的create
和update
方法的应用,所以你并不真的需要通过那些回来。至于@post.id
你可以只存储在您的new
或edit
方法会话变量...
session[post_id] = @post.id
,然后在你的create
或`更新方法...
@post_comment.post_id = session[:post_id]
我完全没有想到'Time.now.utc'可以在控制器内部使用。感谢您发现它。 –
感谢许多清算事情为我。我不知道'post_id'参数会自动传递,现在它更有意义。由于我使用的是设计,不应该是'@post_comment.user_id = current_user.id'(这意味着你的代码行是错误的或者至少不遵循约定) –
只要你有一个'belongs_to:user '在'Comment'模型中,你可以使用'user'或'user_id',他们都会正常工作:) 如果你有一个或者另一个验证 - 使用带验证的验证...(例如'validates_presence_of:user_id'意味着你应该更喜欢'@comment.user_id = current_user.id') –
太好了!由于我们在控制器本身的用户标识中进行了归档,并且我确定该表单仅在用户登录时才可见,因此不需要“validates_presence_of:user_id”权限? –