Ruby on Rails - 仅显示帮助程序中的当前和未来月份

时间:2018-04-27 16:38:38

标签: ruby-on-rails ruby helper

我有一个帮助器,它在选择输入中显示来自事件模型的数月和数年。我如何仅显示当前和未来的月份,而不是过去几个月?

def select_month_tag(events)
  html = <<-HTML
  <select id="filtro-mes-ano" class="event-filter selectCustom2 event_filter_select">
    <option value="Filtrar por mês" disabled selected >Filtrar por mês</option>
  HTML

  events.each do | event |
    if not date_and_month(event.month_ref, event.year_ref).blank?
      html += <<-HTML
        <option data-year="#{event.year_ref}"
          data-month="#{event.month_ref}"
          "#{'selected' if is_hash_selected?(event)}">
          date_and_month(event.month_ref, event.year_ref)}
        </option>
      HTML
    end
  end

  html += <<-HTML
  </select>
  HTML

  html.html_safe
end

感谢。

2 个答案:

答案 0 :(得分:0)

我猜你会为你编写的代码做类似的事情。 如果它对您有用,请告诉我

def select_month_tag(events)
  html = <<-HTML
  <select id="filtro-mes-ano" class="event-filter selectCustom2 event_filter_select">
    <option value="Filtrar por mês" disabled selected >Filtrar por mês</option>
  HTML

  events.each do | event |
    if not date_and_month(event.month_ref, event.year_ref).blank?
      # Get today's date
      today = Date.today

      # check if event year is greater than present date's year
      if event.year_ref >= today.year

        # check if event month is greater than present date's month
        if event.month_ref >= today.month # considering month_ref is a number between 1..12
          html += <<-HTML
            <option data-year="#{event.year_ref}"
              data-month="#{event.month_ref}"
              "#{'selected' if is_hash_selected?(event)}">
              date_and_month(event.month_ref, event.year_ref)}
            </option>
          HTML
        end
      end
    end
  end

  html += <<-HTML
  </select>
  HTML

  html.html_safe
end

答案 1 :(得分:0)

为什么不过滤Event集合,然后用它创建选项?我不认为你在帮手中想要这么多逻辑。最好在模型上创建一个范围,并使用它。像

这样的东西

Event.where('date > ?', date_variable_here)

Can you do greater than comparison on a date in a Rails 3 search?

相关问题