我正在尝试构建一个简单的博客类型的应用程序来学习 Ruby on rails。创建曾经有效,但在添加编辑/更新功能后,创建和编辑都不起作用。我不确定我做错了什么。"编辑"不会使用新数据进行更新,"创建"不再接受新数据。 例如:创建新帖子将导致无论写什么都会导致空白帖子,并且在向旧帖子添加新文本时,点击提交后不会更改帖子。
我的控制器:
def create
@post = Post.create(post_params)
if @post.save(post_params)
redirect_to @post
else
render 'new'
end
end
def show
@post = Post.find(post_params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update_attributes(post_params)
redirect_to @post
else
render 'edit'
end
end
def edit
@post = Post.find(params[:id])
end
def post_params
params.permit(:title, :detail)
end
编辑和创建 html 文件都会呈现表单页面:
<div class="section">
<%= simple_form_for @post do |f| %>
<%= f.input :title %>
<%= f.input :detail %>
<%= f.button :submit %>
<% end %>
</div>
def create
@post = Post.new(post_params) # use Post.new, don't create already
if @post.save # if above Post is saved then redirect
redirect_to @post
else
render 'new'
end
end
def show
@post = Post.find(params[:id]) #use params[:id], not post_params[:id]
end
def update
@post = Post.find(params[:id]) #use params[:id] to find the post
if @post.update_attributes(post_params) #use post_params for attributes
redirect_to @post
else
render 'edit'
end
end
def edit
@post = Post.find(params[:id]) #use params[:id] to find post
end
private
def post_params
params.require(:post).permit(:title, :detail)
# Don't permit the ID as you don't want to change the ID.
end
问题可能出在您的post_params
方法上。我猜您必须先要求:post
键才能允许其属性。通常,simple_form(和其他表单引擎(会像这样组装有效负载:
{
"utf8": "✓",
"authenticity_token": "...",
"commit": "Create Post",
"post": {
"title": "Opa",
"content": "teste"
}
}
因此,如果您params.permit(:title, :detail, :id)
,您将获得一个空哈希。这可能就是帖子使用空属性保存的原因。
你将不得不
params.require(:post).permit(:title, :detail)
默认情况下,URL 参数(您在 /posts/:id
等路由中定义的参数(已被允许,因此您不必允许也不必要求它。