Индекс рендеринга Rails (JSON) после обновления возвращает пустой массив - PullRequest
0 голосов
/ 14 марта 2019

В моем небольшом приложении на 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

1 Ответ

0 голосов
/ 14 марта 2019

Вам необходимо определить @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
...