我的代码:
class Document < ApplicationRecord
belongs_to :series
has_one_attached :file
validates :name, presence: true
end
class MagazineIssue < Document
end
class DocumentsController < ApplicationController
before_action :set_document, only: %i[ show edit update destroy ]
# GET /documents or /documents.json
def index
@documents = Document.all
end
# GET /documents/1 or /documents/1.json
def show
end
# GET /documents/new
def new
@document = Document.new
end
# GET /documents/1/edit
def edit
end
# POST /documents or /documents.json
def create
@document = Document.new(document_params)
respond_to do |format|
if @document.save
format.html { redirect_to document_url(@document), notice: "Document was successfully created." }
format.json { render :show, status: :created, location: @document }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @document.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /documents/1 or /documents/1.json
def update
respond_to do |format|
if @document.update(document_params)
format.html { redirect_to document_url(@document), notice: "Document was successfully updated." }
format.json { render :show, status: :ok, location: @document }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @document.errors, status: :unprocessable_entity }
end
end
end
# DELETE /documents/1 or /documents/1.json
def destroy
@document.destroy!
respond_to do |format|
format.html { redirect_to documents_url, notice: "Document was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_document
@document = Document.find(params[:id])
end
# Only allow a list of trusted parameters through.
def document_params
params.require(:document).permit(:name, :month, :year)
end
end
class MagazineIssuesController < DocumentsController
def show
@magazine_issue = MagazineIssue.find(params[:id])
end
end
我在
show.html.erb
和 views/documents
中也都有一个 views/magazine_issues
文件。
基本上我想要发生的是,如果一种文档(例如“MagazineIssue”)具有一组视图,那么我希望它呈现这些视图。如果没有,那么我希望使用“文档”的后备视图集进行渲染。
现在,我有一个标准文档(数据库中没有设置
type
)和一个 MagazineIssue 类型文档,并且两者都只是使用文档显示视图进行渲染。
如何使用 MagazineIssue 显示视图获取 MagazineIssue 文档?
有几种方法可以回答这个问题!
首先,让我们先解决一件事。如果您访问
GET /documents/1/
,它会调用 DocumentsController#show
。由于您的 show
方法定义为
# GET /documents/1 or /documents/1.json
def show
end
Rails 将默认为
/app/views/documents/show.erb.html
,因为这是约定版本配置默认值。
如果您依次访问
GET /magazine_issues/1
,它将呈现 magazine_issues/show
模板。
怎样才能得到你想要的结果?
DocumentsController#show
def show
render "#{@document.type.underscore.pluralize}/show" # Underscore method will convert MagazineIssue to magazine_issue
end
before_action :redirect_magazine_issues, only: :show
def redirect_magazine_issues
redirect_to magazine_issues_path(@document.id)
end