Rails 更新返回空数组后呈现索引 (JSON)

Rails render index (JSON) after update returning empty array

在我的小型 Rails 应用程序中,我想通过 json 格式更新一个对象,并成功接收 index.json.jbuilder 内容(使用 render :index JSON 更新中的格式)。但出于某种原因,我只是得到一个空数组......我尝试了很多选项但都没有成功,所以欢迎任何帮助!提前致谢

我的路线

resources :coaches, only: [:show] do
  resource :calendar, only: :show, defaults: { format: :json }
  resources :events, only: [:index, :update], defaults: { format: :json }
end

我的控制器

respond_to :json, only: :index

def index
  @events = Event.all
end

def update
  respond_to do |format|
    if @event.update(event_params)
      if params[:commit] == I18n.t('next')
        format.html { redirect_to booking_event_confirm_path(@event) }
      elsif params[:commit] == I18n.t('confirm')
        format.html { redirect_to root_path, notice: "Event was successfully confirmed." }
      else
        format.html { redirect_to booking_event_path(@event), notice: 'Event was successfully updated.' }
        format.json { render :index, status: :ok }
      end
    else
      if params[:commit] == I18n.t('next')
        format.html { render :training }
      elsif params[:commit] == I18n.t('confirm')
        format.html {
          # TODO: why is the url not persistent? ('/confirm' being removed even if page display seems ok)
          render :confirm
        }
      else
        format.html { render :training }
        format.json { render json: @event.errors, status: :unprocessable_entity }
      end
    end
  end
end

您需要在更新操作中定义 @events 以将其呈现为 json

def update
  respond_to do |format|
    if @event.update(event_params)
      if ... 
       ....
      else
        @events = Event.all
        format.json { render :index, status: :ok }
      end
    else
      ....
    end
  end
end