【问题标题】:Rails routing with date and has many带有日期的 Rails 路由并有很多
【发布时间】:2010-12-12 23:11:44
【问题描述】:

我有以下设置:

 map.resources :articles
 map.resources :users, :has_many => [:articles]

这很好,因为我可以通过 /users/2/articles 获取给定用户的文章列表。

我还有一个路线设置要做:

map.connect 'articles/month/:month/:year', :controller => 'articles', :action => 'index'

这适用于查找给定月份和给定年份的所有文章。

我现在要做的是显示给定用户在给定月份和年份的文章。

可能是这样的网址:/users/2/articles/month/4/2009

有没有一种巧妙的方法来做到这一点?谢谢

【问题讨论】:

    标签: ruby-on-rails ruby rest routes


    【解决方案1】:
    map.resources :user do |user|
      user.connect 'articles/:month/:year', :controller => 'articles'
    end
    

    【讨论】:

      【解决方案2】:

      我不倾向于使用基于资源的路由,所以在我看来以下应该可行

      map.connect 'users/articles/:user_id/:month/:year', :controller => 'users', :action => 'articles', :user_id => 0, :month => Time.now.strftime("%m"), :year => Time.now.strftime("%Y")
      

      这应该允许/users/articles/2/11/2009 的网址,并提供当前月份和年份作为默认值,以防您想使用/users/articles/2 作为基本网址,并在您想更具体时提供月份或年份作为附加值.

      它将路由到“用户”控制器和“文章”操作,并将其他值作为 params[] 哈希中的参数

      此外,您应该能够更改连接顺序:

      map.connect 'users/:user_id/articles/:month/:year'
      

      保持其余部分相同以获取网址:/users/2/articles/11/2009

      【讨论】:

      • 我已经使用 map.connect 'users/:user_id/articles/:month/:year' 了,效果很好。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 2017-09-23
      • 2014-02-13
      相关资源
      最近更新 更多