Rails 一个关于 routes 的问题

ryan · 2013年04月27日 · 最后由 tylerlong 回复于 2013年04月27日 · 2030 次阅读

我有一个 collection 模型,拥有 fields 是:

class Collection < ActiveRecord::Base
    attr_accessible :link,:tag,:collection_type,:content
end

:collection_type有 3 种 string 类型的字段,articles,videos,images, 如果我想生成这样的 route: /collections/articles/:id /collections/videos/:id /collections/images/:id 那我的 routes 要如何设置呢?

还有就是如果我想批量显示 articles,那是否可以生成这样的 url: /collections/articles

我现在的 route 是这样写的

resources :collections do
    member do
     get 'articles'
     get 'videos'
     get 'images'
   end
end

但是毕竟这样的话,就属于硬编码了,扩展性不佳。是否有改进之处?我想到的是把 collection_type 也作为一种 resources 来处理。

经过修改,得到了预期的 url routes 映射

resources :users do
  resources :collections do
    get 'articles',on: :collection
    get 'videos', on: :collection
    get 'images', on: :collection
  end
end

以上代码就可以映射出

articles_user_collections GET    /users/:user_id/collections/articles(.:format) collections#articles
  videos_user_collections GET    /users/:user_id/collections/videos(.:format)   collections#videos
  images_user_collections GET    /users/:user_id/collections/images(.:format)   collections#images

虽然得到了预期的效果,但是'articles','videos'和'images'依然是硬编码,能否通过某种途径利用 collection 模型的 collection_type 字段来取代这三个值呢?

感觉可以用 class Article < Collection 然后直接使用 rails 内置的 type 字段,这样就可以直接 Article.find params[:id],其它做法和普通 model 一样。

#1 楼 @iBachue 参数是指 params[:collection_type] 这样写在 erb 里面还是写在 routes 里面?

#3 楼 @Ryan params 可以写在 controller 里或是 view 里 routes 里的写法务必参考http://guides.rubyonrails.org/routing.html

#4 楼 @iBachue params 我知道,这篇文章我看过了,似乎并没有提到利用模型的字段来作为 url 的一部分。

#5 楼 @Ryan 文章当然没有提到 不可能每种需求设计者都考虑到的 但是它告诉你参数在 routes 里是怎么处理又是怎么交给 controller 的,那个就足够了,接下来就是你如何利用这个特性来实现你的功能了。

#2 楼 @prajnamas 确实至少在 url 里面成功建立了所需的东西。

还有一种选择是用多态。拆分三个东西到三个不同的 model 中去。共有部分抽出来成为一个新的 model. 参考 http://guides.rubyonrails.org/association_basics.html#polymorphic-associations 按照它的例子:Employee 和 Product 是两个 model, 他们共有的部分是 Picture. 可能会增大复杂度,慎用。

#8 楼 @tylerlong 好像有点负责。。。而且主要是现在数据库中表和 model 是一一对应的,这样拆分,是不是表也被同样的拆分了。migration 也要重新来过?

#9 楼 @Ryan 是的。整个全变了。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号