Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在Ruby On Rails上循环数年和数月_Ruby On Rails_Ruby On Rails 3_Loops - Fatal编程技术网

Ruby on rails 在Ruby On Rails上循环数年和数月

Ruby on rails 在Ruby On Rails上循环数年和数月,ruby-on-rails,ruby-on-rails-3,loops,Ruby On Rails,Ruby On Rails 3,Loops,我已经和代码斗争了好几天了,我真的不能从中得到任何好处 我正在制作一个博客档案,我正在寻找一种方法,从创建的网站上获取所有的年和月。假设我从2011年、2012年和2013年收到了很多帖子 下面的“代码”只是我试图构建的结构的一个示例(这只是为了让您了解我希望它看起来像什么) 我所追求的输出类似于: 2013 May Name of post Name of post April Name of post Name of post Mars N

我已经和代码斗争了好几天了,我真的不能从中得到任何好处

我正在制作一个博客档案,我正在寻找一种方法,从创建的网站上获取所有的年和月。假设我从2011年、2012年和2013年收到了很多帖子

下面的“代码”只是我试图构建的结构的一个示例(这只是为了让您了解我希望它看起来像什么)

我所追求的输出类似于:

2013
  May
    Name of post
    Name of post
  April
    Name of post
    Name of post
  Mars
    Name of post
    Name of post

2012
  December
    Name of post
    Name of post
  November
    Name of post
    Name of post
  October
    Name of post
    Name of post

我希望我说得够清楚了!我相信这比我现在想的要简单得多!非常感谢您的帮助

稍加修改,效果很好!简单又好,就像我想要的那样。我从来没有想到在所有帖子的循环中使用if语句。。。非常感谢您的快速和良好的awnser!稍加修改,效果很好!简单又好,就像我想要的那样。我从来没有想到在所有帖子的循环中使用if语句。。。非常感谢您的快速和良好的awnser!
month, year = nil, nil
Post.order("created_at desc") do |post|
  if year != post.created_at.year
    year = post.created_at.year
    puts year
  end

  if month != post.created_at.month
    month = post.created_at.month
    puts "\t#{post.created_at.strftime("%B")}"
  end

  puts "\t\t#{post.name}"
end
month, year = nil, nil
Post.order("created_at desc") do |post|
  if year != post.created_at.year
    year = post.created_at.year
    puts year
  end

  if month != post.created_at.month
    month = post.created_at.month
    puts "\t#{post.created_at.strftime("%B")}"
  end

  puts "\t\t#{post.name}"
end