2015-10-19 65 views
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篩選職位和月份顯示他們一個月:

enter image description here

我已經開始實施這一如下:

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) %> 

(後來才知道有一個循環來顯示相關文章)。

上面的代碼在當年運行得非常好,即我可以按月導航,每個月我都會得到正確的帖子。但是,當我嘗試導航到上一年(點擊「<上一個」按鈕幾次)或到下一年(點擊幾次「<上一個」按鈕)時,則有兩件事情發生:

enter image description here

  • 月份序列從2015年1月進入到2014年12月至2015年11月(或2015年12月至2016年1月至2015年2月),這意味着@current_year不再正確。
  • 因此(這實際上是一個表明查詢工作正常的標誌),因爲我不再導航到2014年11月,而是去2015年11月,因此顯示2015年11月的帖子(相同問題與2016年2月比2015年2月)。

任何想法我的代碼有什麼問題?

回答

2

我想你也必須通過@current_yearcalendar_path。看起來這種情況始終將2015年定爲當年。

@current_year = params[:year].blank? ? Date.today.year : params[:year].to_i 

,因爲它的工作原理與十二月和一月的原因是因爲你改變了本年度月份時爲0 or 13

這應該工作

<%= link_to '< Previous', calendar_path(@calendar, month: @current_month - 1, year: @current_year) %> 

<%= link_to 'Next >', calendar_path(@calendar, month: @current_month + 1, year: @current_year) %> 
+0

謝謝你這麼多。你是完全正確的,無論是在你的問題識別和解決方法。一切都在工作。 –