在Rails中,创建具有草稿状态的新记录通常涉及到使用一个表示状态的字段,比如status
。这个字段可以有不同的值来表示记录的不同状态,例如“草稿”、“已发布”等。
状态字段通常是字符串或枚举类型。例如:
# 字符串类型
rails generate model Post title:string content:text status:string
# 枚举类型
rails generate model Post title:string content:text status:enum { draft published archived }
假设我们有一个博客系统,需要创建一个具有草稿状态的新文章。
# app/models/post.rb
class Post < ApplicationRecord
enum status: { draft: 0, published: 1 }
end
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def new
@post = Post.new(status: :draft)
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: 'Post was successfully created.'
else
render :new
end
end
private
def post_params
params.require(:post).permit(:title, :content, :status)
end
end
<!-- app/views/posts/new.html.erb -->
<h1>New Post</h1>
<%= form_with(model: @post, local: true) do |form| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :title %>
<%= form.text_field :title %>
</div>
<div class="field">
<%= form.label :content %>
<%= form.text_area :content %>
</div>
<div class="field">
<%= form.label :status %>
<%= form.select :status, Post.statuses.keys %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
原因:可能是由于表单中没有包含状态字段,或者控制器中的参数验证没有通过。
解决方法:
# 确保表单中包含状态字段
<%= form.select :status, Post.statuses.keys %>
# 确保控制器中包含状态字段的验证
def post_params
params.require(:post).permit(:title, :content, :status)
end
通过以上步骤,你可以轻松地在Rails中创建具有草稿状态的新记录,并确保其正确保存和使用。
没有搜到相关的文章