【发布时间】: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