【发布时间】:2010-06-03 17:36:03
【问题描述】:
目前用户可以通过多种途径访问他们的“个人资料”。
- localhost:3000/users/current_user
- localhost:3000/users/current
- localhost:3000/users/id#
我怎样才能让他们只能通过 localhost:3000/users/current_user 访问他们的“个人资料”
【问题讨论】:
标签: ruby-on-rails ruby
目前用户可以通过多种途径访问他们的“个人资料”。
我怎样才能让他们只能通过 localhost:3000/users/current_user 访问他们的“个人资料”
【问题讨论】:
标签: ruby-on-rails ruby
关于您的问题的“内容”的一个建议:我建议使用 localhost:3000/user 或更具描述性的内容,而不是理想的 url,例如 >localhost:3000/profile 或 localhost:3000/account。
您能否在您的 routes.rb 中包含这些条目?即使 Authlogic 等将路由添加到您的应用程序,它们也应该在 routes.rb 中进行。如果你有条目:
map.resource :users
那么这就是 /users/123 路由的来源。我同意 Matchu 的观点,即使您不使用 /users/123 您也应该保留它并将其他请求路由到它。
另一个想法 如果您不想进入跨重定向保留模型验证错误的业务(有点复杂,而且不漂亮),这里有另一种方法。我从这里假设您已经拥有 map.resource :users,因此您的 UsersController 上有 7 个默认操作(索引、新建、创建、显示、编辑、更新、销毁)。
在你的 routes.rb 中:
map.profile 'profile', :controller => 'users', :action => 'show'
map.edit_profile 'profile/edit', :controller => 'users', :action => 'edit', :conditions => { :method => :get }
map.update_profile 'profile/edit', :controller => 'users', :action => 'update', :conditions => { :method => :put }
你需要稍微更新你的 form_for 标签:
<% form_for @user, :url => update_profile_path do |f| %> ...
现在,假设您从 /profile 开始,然后单击将您带到 /profile/edit 的编辑链接(应该显示表单),如果您填写的表单导致验证失败,那么您应该最终回到/profile/edit 在 f.error_messages 输出中使用正确的错误。
您用于编辑的控制器代码应保持不变,您的更新代码应为:
def update
@user = current_user || User.find(params[:id])
if @user.update_attributes(params[:user])
flash[:notice] = "Successfully updated user."
redirect_to @user
else
render :action => 'edit'
end
end
渲染(而不是重定向)保留@user 模型的状态(包括错误),并且只是再次渲染编辑模板。由于您将其指向 update_profile_path,因此用户查看的 url 仍然是 /profile/edit。
【讨论】:
嗯,首先,删除/users/current 路由,你必须在你的routes.rb 某处。 (虽然我更喜欢/users/current 而不是/users/current_users,因为后者相当多余。)
至于/users/123,在你的控制器中,你可以检查当前用户的ID是否匹配123或其他,如果匹配,则重定向。
但我真的更喜欢相反的效果。将/users/current 推送到/users/123 在我的大脑中更有意义,因为它使所有用户的路线保持一致,同时仍然允许您缓存指向/users/current 的链接。
【讨论】:
rake routes 以查看是否以某种方式插入了路由。也许User.find('current') 返回当前用户?