1
在我的Rails應用4,我有以下型號:軌道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月)。
任何想法我的代碼有什麼問題?
謝謝你這麼多。你是完全正確的,無論是在你的問題識別和解決方法。一切都在工作。 –