将用户设置为他们自己的视图/关联
问题描述:
我正在使用设计进行身份验证,并在用户(has_many :products
)和产品模型(belongs_to :user
)之间建立关联。将用户设置为他们自己的视图/关联
我的路线文件
resources :users do
resources :products
end
现在是什么情况,id为3的用户在/users/3/products
也可以看到最新的/users/4/products
。我想限制这一点。我不想/users/3/products
能够看到什么在/users/4/products
等(不是特定于这两个用户,但为所有)。我该怎么做 ?我应该有一个用户控制器吗?我现在没有。如果我有控制器,我该怎么做?我在想也许重定向它?
感谢
答
你可以在你的产品控制器添加before_filter
:
class ProductsController < ApplicationController
before_filter :user_is_current_user
...
private
def user_is_current_user
unless current_user.id == params[:user_id]
flash[:notice] = "You may only view your own products."
redirect_to root_path
end
end
end
此外,在产品的控制,你可以只检索产品属于current_user
:
def index
@products = current_user.products # will fetch all products with a user_id matching the current user's
end
如果你使用上述你不需要在URL中的用户ID,你可以使用路径/users/products
或只是/products
。
实际上,我需要的ID,我将稍后转换成用户名(使用slu((友好的身份证宝石)) – psharma 2013-05-05 07:36:27
现在发生的是,我甚至不能进入/用户/:ID /产品视图。它将所有的重定向到root_path – psharma 2013-05-05 07:38:37
对不起,这可能应该是'params [:user_id]''不只是'[:id]'。我已经更新了我的答案。您也可以更改过滤器以允许管理员用户查看全部。 – 2013-05-05 07:45:11