【问题标题】:Rails render index (JSON) after update returning empty array更新后的 Rails 渲染索引(JSON)返回空数组
【发布时间】:2019-03-14 02:12:04
【问题描述】:

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

我的路线

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

【问题讨论】:

  • index.json.jbuilder 里面有什么?我想您需要在 udate 操作中定义 @events 来解决问题
  • @Vasilisa 如果我是对的,@events 已经在 def index 中定义了,不是吗?
  • 是的,它已定义,但您正在进行创建操作
  • 天哪,你是对的!我在我的更新方法(操作)中添加了一个 @events = Event.all就在 format.json 行之前,它起作用了!但是这样做是不是有点难看?也许有一个更清洁的方法(渲染方法的参数......)?无论如何,谢谢你的帮助!
  • 当你渲染不同的模板时,这是常见的方式

标签: ruby-on-rails json jbuilder


【解决方案1】:

您需要在更新操作中定义@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

【讨论】:

  • 你是对的,谢谢!顺便说一句,您认为有更好的方法来定义该变量吗?我认为render :index 会自动调用其中定义的@events。无论如何,再次感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
相关资源
最近更新 更多