You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Ruby on Rails应用中实现simple_calendar时遇NoMethodError求助

Fixing "undefined method `reject' for nil:NilClass" with simple_calendar in Rails

Hey there, let's get this calendar issue sorted out! That error might seem confusing since you don't have reject in your own code, but it's actually coming from the simple_calendar gem itself. Here's what's happening and how to fix it:

Why this error happens

The month_calendar helper expects a collection of events (like an ActiveRecord relation or array) passed to the events: parameter. When you pass @events and that variable is nil (because it wasn't set in your controller), the gem tries to call reject on nil—hence the error.

Step 1: Check your controller's action

First, make sure you're assigning @events in the controller action that renders your calendar view (usually the index action). For example:

# app/controllers/events_controller.rb
class EventsController < ApplicationController
  def index
    # Fetch all events, or add your own filtering logic here
    @events = Event.all
  end
end

If you skip this assignment, @events will be nil by default, which breaks the calendar helper.

Step 2: Add a fallback for nil events

If there's a chance @events might be nil even with proper controller setup (like in edge cases), you can pass an empty array as a fallback directly in the view:

<%= month_calendar events: @events || [] do |date, events| %>
  <%= date.day %>
  <% events.each do |event| %>
    <div><%= event.name %></div>
  <% end %>
<% end %>

This ensures the gem always gets a valid collection (even if it's empty) instead of nil.

If you're fetching events through an association (like @user.events), double-check that the parent record (e.g., @user) exists and the association is correctly defined in your models. A nil parent will result in nil events.

That should resolve the error! Start with checking the controller assignment—it's the most common culprit here.

内容的提问来源于stack exchange,提问作者G.Hines

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:46:29