如何在具有嵌套模型的控制器中使用respond_with

时间:2012-12-16 03:13:22

标签: ruby-on-rails ruby-on-rails-3

我的报告模型有很多区域。

在尝试将其切换为使用新的respond_with样式之前,areas_controller.rb工作正常。

切换后,创建和索引操作仍然可以正常工作,但编辑操作实际上并未更新区域,尽管发送了闪存消息“区域已成功更新”。为什么呢?

areas_controller.rb

class AreasController < ApplicationController

  respond_to :html
  filter_resource_access
  layout "wide"

  def index
    @report = Report.find(params[:report_id])
    @areas = @report.areas
    respond_with(@report, @areas)
  end

  def show
    @report = Report.find(params[:report_id])
    @area = @report.areas.find(params[:id])
    respond_with(@report, @area)
  end

  def new
    @report = Report.find(params[:report_id])
    @area = @report.areas.build
    respond_with(@report, @area)
  end

  def create
    @report = Report.find(params[:report_id])
    @area = @report.areas.build(params[:area])
    flash[:notice] = "Area was successfully created." if @area.save
    respond_with(@report, @area)
  end

  def edit
    @report = Report.find(params[:report_id])
    @area = @report.areas.find(params[:id])
    respond_with(@report, @area)
    #also tried leaving that respond_with out
  end

  def update
    @report = Report.find(params[:report_id])
    @area = @report.areas.find(params[:id])
    flash[:notice] = "Area was successfully updated." if @area.save
    respond_with(@report, @area, :location => report_area_path(@report, @area))
    # also tried respond_with(@report, @area)
  end

  def destroy
    @report = Report.find(params[:report_id])
    @area = @report.areas.find(params[:id])
    @area.destroy
    respond_with(@report, @area)
  end

end

1 个答案:

答案 0 :(得分:1)

您需要更新模型上的属性:

def update
  @report = Report.find(params[:report_id])
  @area = @report.areas.find(params[:id])
  flash[:notice] = "Area was successfully updated." if @area.update_attributes(params[:area])
  respond_with(@report, @area, :location => report_area_path(@report, @area))
end