路由:组合资源和嵌套资源

时间:2011-04-14 12:18:06

标签: ruby-on-rails ruby-on-rails-3

/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

2 个答案:

答案 0 :(得分:4)

它看起来很丑,但这是我的第一个想法:)

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

或者你可以蛮力:解析你的请求网址:)。

答案 1 :(得分:2)

我通过将代码分成两个控制器(一个命名空间)来解决这个问题。我认为这比将条件逻辑添加到单个控制器更清晰。

# routes.rb
resources :items
namespace 'user' do
  resources :items
end

# items_controller.rb
class ItemsController < ApplicationController
  def index
    @items = Item.all
  end
end

# user/items_controller.rb
class User::ItemsController < ApplicationController
  def index
    @items = current_user.items
  end
end
相关问题