【问题标题】:Namespaced resources命名空间资源
【发布时间】:2009-11-30 18:16:12
【问题描述】:

这是我的 config/routes.rb 文件的摘录:

resources :accounts do |account|

      account.resource :profile, :except => [:new, :create, :destroy]

      account.resources :posts,
                        :collection => { :fragment => :get },
                        :has_many => [:comments, :likes]

      # even more code

end

我希望从帐户命名空间(例如 Account::PostsController 而不是 PostsController)加载每个嵌套资源。

使用资源 :accounts, :namespace => 'account' 尝试加载 AccountPostsController。

试图嵌套结构并不能很好地工作:

map.namespace :account do |account|
..
end

前面的代码将从我想要的位置加载文件,但它确实将命名空间添加到 url 和生成的路径中,因此我将拥有诸如 account_account_posts_url 和类似路径之类的方法。

另一种选择是使用类似的东西:

account.resource :profile, :controller => 'account/profile'

我真的不喜欢这样,因为它既涉及代码重复,又迫使我删除一些 rails 魔术助手。

有什么想法和建议吗?

【问题讨论】:

  • 查看我的更新以了解应该可以使用的内容。

标签: ruby-on-rails namespaces


【解决方案1】:

这样的事情怎么样?

map.resources :accounts do |accounts|
  accounts.with_options(:namespace => "account") do |account|
    account.resource :profile, :except => [:new, :create, :destroy]
    ...
  end
end

我还没有尝试过,所以不知道它是否会起作用,但这是一个开始。请参阅Rails Routing,了解有关 Rails Routes 可以做什么的更多详细信息和选项。

投反对票后

所以我进行了一些测试。更改我的 routes.rb 并运行 rake routes 并提出以下内容(非常接近我必须开始的内容):

map.resources :accounts do |accounts|
  accounts.namespace :account do |account|
    account.resource :profile, :except => [:new, :create, :destroy]
  end
end

这会让你得到你想要的。正确的 url 并指向 account/... 控制器。

【讨论】:

  • 非常感谢。我不知道是谁修改了你,但你肯定会得到我的 +1。
  • 不用担心。很高兴您获得了所需的路线定义。下降标记很可能是由于I haven't tried this so have no idea if it will work 声明。
【解决方案2】:

那么命名空间有什么特别的问题?我认为这就是你想要做的:

map.namespace :account do |account|
  account.resource :profile
end

这将尝试在 app/controllers/account/profiles_controller.rb 加载控制器,并将生成诸如 account_profile_path 之类的路由。

根据评论更新

map.resources :accounts do |account| 
 account.resource :profile
end

会给你/accounts/22/profile

【讨论】:

  • 感谢您的回复。很抱歉没有说清楚,但我所追求的是如下所示的路线:/accounts/22/profile 上面的代码将生成帐户/个人资料。
猜你喜欢
  • 1970-01-01
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-12
  • 2011-07-06
  • 1970-01-01
相关资源
最近更新 更多