/items
应该列出所有项目
/user/items
应该只列出当前用户的项目
我已经定义了用户和项目之间的关系,所以 current_user.items
工作正常。
我的问题是:
items#index
操作如何知道它是被直接调用还是通过用户资源调用,以便知道用什么填充 @items
?
# routes.rb
resources :items
resource :user do
resources :items
end
# items_controller.rb
class ItemsController < ApplicationController
def index
@items = Item.all
end
end
# users_controller.rb
class UsersController < ApplicationController
def show
@user = current_user
end
end
最佳答案
它看起来很老套,但这是我的第一个想法:)
resource :user do
resources :items, :i_am_nested_resource => true
end
class ItemsController < ApplicationController
def index
if params[:i_am_nested_resource]
@items = current_user.items
else
@items = Item.all
end
end
end
或者您可以采用蛮力的方式:解析您的请求 url :)。
关于ruby-on-rails - 路由 : Combining resources and nested resources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5663096/