2010-03-17 51 views
5

我有一個相當簡單的模型;用戶擁有多個產品。我希望能夠查看所有產品的列表以及與給定用戶關聯的產品列表。我的路由設置是這樣的:Rails中嵌套資源視圖的最佳實踐?

/products 
/products/:id 
/users 
/users/:id 
/users/:id/products 

的這裏美中不足的是,我想在產品#指數視圖和用戶/產品#指數視圖顯示不同的產品列表中。

有沒有一種「正確」的方法來做到這一點?我目前的解決方案是將產品定義爲用戶內部的嵌套資源,然後檢查params [:user_id] - 如果找到了我提供的模板,名爲'index_from_user',否則我只呈現典型的'index'模板。

這是我遇到了很多的情況 - 如果有這樣做的優選方式我很想知道......

+0

它通常被認爲是「接受」解決問題的答案的好形式。你可以通過點擊答案旁邊的「打勾」來做到這一點:) – 2011-11-16 18:14:21

回答

2

可以申報兩個「產品」路線 - 一個在用戶,和一個獨立的用戶,例如:

map.resources:產品 map.resources:用戶:的has_many =>:產品

他們都將尋找 「的ProductsController#指數」,但第二次將有「 user_id「(注意:」user_id「不只是」id「)

所以你可以在索引方法中測試它,並根據它是否存在顯示不同的項目。

您將需要一個的before_filter添加到ProductController的實際實例化用戶模型,然後才能使用它例如:

before_filter :get_user # put any exceptions here 

def index 
    @products = @user.present? ? @user.products : Product.all 
end 

# all the other actions here... 


# somewhere near the bottom... 
private 

def get_user 
    @user = User.find(params[:user_id]) 
end 

如果你真的想顯示完全不同的看法,你可以做它明確在指數行動中,例如:

def index 
    @products = @user.present? ? @user.products : Product.all 
    if @user.present? 
    return render(:action => :user_view) # or whatever... 
    end 
    # will render the default template... 
end