【发布时间】:2015-10-19 16:36:48
【问题描述】:
在我的 Rails 4 应用程序中,我有以下模型:
class Calendar < ActiveRecord::Base
has_many :administrations
has_many :users, through: :administrations
has_many :posts
has_many :comments, through: :posts
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
class Post < ActiveRecord::Base
belongs_to :calendar
has_many :comments
end
post 对象以它们所属日历的Calendars#Show 视图显示。
每个帖子都有一个:date 自定义属性(与:created_at 默认属性不同)。
我想在Calendars#Show 视图中实现导航,让我可以按:date 过滤帖子并逐月显示:
我已经开始按如下方式实现:
在calendars_controller.rb,我有:
def show
@user = current_user
@calendar = @user.calendars.find(params[:id])
@current_month = params[:month].blank? ? Date.today.month : params[:month].to_i
@current_year = params[:year].blank? ? Date.today.year : params[:year].to_i
if @current_month == 13
@current_month = 1
@current_year = @current_year + 1
end
if @current_month == 0
@current_month = 12
@current_year = @current_year - 1
end
@posts = @calendar
.posts
.includes(:comments)
.where("Extract(month from date) = ?", @current_month)
.where("Extract(year from date) = ?", @current_year)
.order "date DESC"
# authorize @calendar
end
在日历show.html.erb 文件中,我有:
<%= link_to '< Previous', calendar_path(@calendar, month: @current_month - 1) %>
<%= "#{Date::MONTHNAMES[@current_month]} #{@current_year}" %>
<%= link_to 'Next >', calendar_path(@calendar, month: @current_month + 1) %>
(然后我有一个循环来显示相关帖子)。
上面的代码在今年运行良好,即我可以逐月导航,每个月我都会得到正确的帖子。
但是,当我尝试导航到上一年(点击“
- 月份顺序从 2015 年 1 月到 2014 年 12 月到 2015 年 11 月(或从 2015 年 12 月到 2016 年 1 月到 2015 年 2 月),这意味着 @current_year 不再正确。
- 因此(这实际上表明查询运行良好),我再次收到相同的帖子,因为我没有导航到 2014 年 11 月,而是转到 2015 年 11 月,因此显示了 2015 年 11 月的帖子(相同2016 年 2 月与 2015 年 2 月的问题)。
知道我的代码有什么问题吗?
【问题讨论】:
标签: ruby-on-rails date ruby-on-rails-4 filter navigation