【问题标题】:Rails 4: filter objects by custom attributes in show viewRails 4:在显示视图中按自定义属性过滤对象
【发布时间】: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


    【解决方案1】:

    我认为您也必须将@current_year 传递给calendar_path。看起来这个条件总是将 2015 年设置为当前年份。

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

    因为它适用于 12 月和 1 月的原因是因为当月份为 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) %>
    

    【讨论】:

    • 非常感谢。你是完全正确的,无论是在你对问题的识别和解决问题的方法上。现在一切正常。
    猜你喜欢
    • 2016-02-20
    • 2016-08-23
    • 1970-01-01
    • 2015-11-02
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    相关资源
    最近更新 更多