Ruby on Rails中如何实现模型全记录的增删改查表单?
嘿,这个需求完全不用手动写所有表单或者依赖JS来处理核心操作哦!Rails的表单助手其实天生就支持独立模型的CRUD,而且实现起来非常常规,我给你一步步拆解下:
首先给你的独立模型(假设叫Template)生成标准的CRUD路由,在config/routes.rb里添加:
resources :templates
这会自动生成index(列表)、new(新建)、create(保存新建)、edit(编辑)、update(保存编辑)、destroy(删除)这6个核心路由,完全满足你的需求。
创建app/controllers/templates_controller.rb,把各个动作的逻辑写好:
class TemplatesController < ApplicationController # 展示所有模板记录 def index @templates = Template.all # 如果要在列表页直接加新建表单,就初始化一个新实例 @template = Template.new end # 初始化新建表单的实例 def new @template = Template.new end # 处理新建记录的提交 def create @template = Template.new(template_params) if @template.save redirect_to templates_path, notice: '模板创建成功!' else # 保存失败就回到表单页面显示错误 render :new # 如果是在index页提交的,就render :index end end # 初始化编辑表单的实例 def edit @template = Template.find(params[:id]) end # 处理编辑记录的提交 def update @template = Template.find(params[:id]) if @template.update(template_params) redirect_to templates_path, notice: '模板更新成功!' else render :edit end end # 处理删除操作 def destroy @template = Template.find(params[:id]) @template.destroy redirect_to templates_path, notice: '模板已删除!' end private # 强参数,限制允许提交的字段 def template_params params.require(:template).permit(:name, :content, # 替换成你的模型字段 :other_field) end end
Rails的表单助手根本不需要依赖其他模型关联,只要有当前模型的实例(不管是新记录还是已存在的记录)就能正常工作,我们可以把表单抽成局部模板复用:
新建/编辑表单局部模板(app/views/templates/_form.html.erb)
<%= form_with(model: @template) do |form| %> <% if @template.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@template.errors.count, "error") %>禁止保存此模板:</h2> <ul> <% @template.errors.each do |error| %> <li><%= error.full_message %></li> <% end %> </ul> </div> <% end %> <!-- 替换成你的模型字段 --> <div class="field"> <%= form.label :name %> <%= form.text_field :name %> </div> <div class="field"> <%= form.label :content %> <%= form.text_area :content %> </div> <div class="actions"> <%= form.submit %> </div> <% end %>
列表页面(app/views/templates/index.html.erb)
这里展示所有记录,同时可以加编辑、删除链接,如果之前在index动作里初始化了@template,还能直接嵌入新建表单:
<h1>所有模板</h1> <!-- 如果要在列表页直接新建,就渲染表单 --> <h2>新建模板</h2> <%= render 'form' %> <table> <thead> <tr> <th>名称</th> <th>内容</th> <th>操作</th> </tr> </thead> <tbody> <% @templates.each do |template| %> <tr> <td><%= template.name %></td> <td><%= template.content %></td> <td> <%= link_to '编辑', edit_template_path(template) %> <%= link_to '删除', template_path(template), method: :delete, data: { confirm: '确定要删除这条记录吗?' } %> </td> </tr> <% end %> </tbody> </table>
新建页面(app/views/templates/new.html.erb)
如果不想在列表页新建,单独的新建页面只要渲染局部表单就行:
<h1>新建模板</h1> <%= render 'form' %>
编辑页面(app/views/templates/edit.html.erb)
同理,编辑页面也是渲染同一个局部表单:
<h1>编辑模板</h1> <%= render 'form' %>
你之前担心的“Rails表单助手需要关联记录”是误解啦!表单助手只需要当前模型的实例——新建时用Template.new,编辑时用从数据库找到的实例,完全不需要和其他模型关联就能正常生成表单、处理提交。删除操作的link_to用method: :delete后,Rails会自动生成JS来发送DELETE请求,不用你自己写JS逻辑。
这样一套下来,查看、新建、编辑、删除所有操作都用Rails原生工具搞定,既省心又符合Rails的最佳实践。
内容的提问来源于stack exchange,提问作者Abhishek Bhatta

