通常這些值不是通過表單傳遞,而是通過使用嵌套的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
感謝許多清算事情爲我。我不知道'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」權限? –