ruby-on-rails - 可以在 rails 中同时使用嵌套和浅层资源吗?如何编写 Controller / View ?

标签 ruby-on-rails resources controller nested

我有资源,将它们分别与其他资源嵌套和分开处理是非常有意义的。 IE。我希望使用所有这样的网址:

/account/4/transfers   # all transfers which belong to an account
/user/2/transfers      # all transfers input by specific user
/project/1/transfers   # all transfers relevant to a project
/transfers             # all transfers

我关心的是如何编写 TransfersController 操作(例如索引),因为它会使父模型中的逻辑加倍 - 有没有比做类似的事情更好的方法
TransfersController
...
def index
  if !params[account_id].nil?
    @account = Account.find(params[account_id])
    @transfers = @account.transfers
  elsif !params[user_id].nil?
    @user = User.find(params[user_id])
    if @user.accesible_by?(current_user)
      @transfers = @user.transfers
    end
  elsif !params[projects_id].nil?
    .....

View 也是如此——尽管它们都会列出传输,但它们对于用户、帐户、项目等会有非常不同的标题、导航等......

我希望你能从这个例子中看到模式。我认为应该有一些非丑陋的解决方案。基本上,我希望将选择要显示的传输的逻辑与其他内容(如 View 的上下文特定部分)分开。

最佳答案

我有一个悬而未决的问题。在我的问题中,我概述了我提出的两种方法。我目前正在使用第二个,并且运行良好。

Routing nested resources in Rails 3

我使用的路线有点不同,因为我使用用户名代替 ID,我首先需要它们。你会坚持这样的事情:

namespace :projects, :path => 'projects/:project_id' do
  resources :transfers #=> controllers/projects/transfers_controller.rb
end

# app/controllers/projects/transfers_controller.rb
module Projects
  class TransfersController < ApplicationController
    # actions that expect a :project_id param
  end
end

# app/controllers/transfers_controller.rb
class TransfersController < ApplicationController
  # your typical actions without any project handling
end

我使用命名空间而不是调用 resources 的原因是让 Rails 让我使用带有单独 View 的单独 Controller 来处理相同的模型,而不是将所有讨厌的条件逻辑推送到我的 Controller 操作中。

关于ruby-on-rails - 可以在 rails 中同时使用嵌套和浅层资源吗?如何编写 Controller / View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5086095/

相关文章:

ruby-on-rails-3 - 设计: Sign in from a controller

javascript - AngularJS - 无法访问 RootScope

ruby-on-rails - HAML:创建 data-xxx-yyy 属性

ruby-on-rails - Rails 4 不存储数据、种子或默认模型保存

ruby-on-rails - 使用 ActiveRecord 确保方法内的事务

javascript - $resource 在 AngularJS 中响应一个空数组

c# - 使用 Visual Studio 以不同语言运行 C# 应用程序

ruby-on-rails - 是否可以保证 ActiveRecord 返回按 ID 排序的对象?

c++ - 资源编译器无法编译 Win32 资源脚本中的枚举语句?

iphone - IOS - 将子 Controller / View 加载到 View 中