简体   繁体   中英

How to use respond_with in a controller with nested models

My Report model has_many areas.

The areas_controller.rb was working fine before I tried switching it to use the new respond_with style.

After switching, the create and index actions still work fine, but the edit action does not actually update the area, despite sending the flash message "Area was successfully updated." Why?

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

You need to update the attributes on the model:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM