To keep to restfull protocol, I need to do /api/backup_jobs/777/errors
.
In rails, the parent controller- I have:
module Api
class BackupJobsController < ApplicationController
respond_to :json
def show
@backup_job = @backup_jobs.find(params[:id])
respond_with data: @backup_job
end
end
end
in the child controller:
module Api
class ErrorsController < BackupJobsController
respond_to :json
def index
respond_with data: @backup_jobs.find(params[:id]).backup_events.errors
end
end
end
But obvisouley this isn't going to work because params[]
doesn't exist for /api/backup_jobs/777/errors
@backup_job = @backup_jobs.find(params[:id])
from the parent controller's def show
to the child controller and have it accessible in the child's def index
? You cannot do that because when an ErrorsController is created and used, you will not have a BackupsJobsController that ran before it.
This comes down to the nature of HTTP being a request-response protocol.
Instead, you can extract the line of code you wrote into a method that will be inherited by the ErrorsController.
backup_jobs_controller.rb :
module Api
class BackupJobsController < ApplicationController
def show
find_backup_job
respond_with data: @backup_job
end
protected
def find_backup_job
@backup_job = @backup_jobs.find(params[:id])
# or maybe @backup_job = BackupJob.find(params[:id])
end
end
end
errors_controller.rb :
module Api
class ErrorsController < BackupJobsController
respond_to :json
def index
respond_with data: find_backup_job.backup_events.errors
end
protected
def find_backup_job
@backup_job = BackupJob.find(params[:backup_job_id])
end
end
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.