我有资源,将它们分别与其他资源嵌套和分开处理是非常有意义的。 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/