2013-05-05 48 views
1

我正在使用設計進行身份驗證,並在用戶(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等(不是特定於這兩個用戶,但爲所有)。我該怎麼做 ?我應該有一個用戶控制器嗎?我現在沒有。如果我有控制器,我該怎麼做?我在想也許重定向它?

感謝

回答

3

你可以在你的產品控制器添加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

+0

實際上,我需要的ID,我將稍後轉換成用戶名(使用slu((友好的身份證寶石)) – psharma 2013-05-05 07:36:27

+0

現在發生的是,我甚至不能進入/用戶/:ID /產品視圖。它將所有的重定向到root_path – psharma 2013-05-05 07:38:37

+0

對不起,這可能應該是'params [:user_id]''不只是'[:id]'。我已經更新了我的答案。您也可以更改過濾器以允許管理員用戶查看全部。 – 2013-05-05 07:45:11

相關問題