在Ruby on Rails中,表单提交后无法更新视图的问题通常是由于缺少相应的控制器和视图逻辑造成的。下面是一个可能的解决方案,包含代码示例:
posts_controller.rb
中添加一个update
动作:class PostsController < ApplicationController
def update
@post = Post.find(params[:id])
if @post.update(post_params)
redirect_to @post
else
render :edit
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
在上面的代码中,我们从数据库中找到要更新的post
对象,并使用update
方法来保存更改。如果更新成功,我们将重定向到@post
的显示页面;如果更新失败,我们将重新渲染编辑页面。
edit.html.erb
视图中,确保表单的action
属性指向正确的控制器动作:<%= form_for @post, url: post_path(@post), method: :patch do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :content %>
<%= f.text_area :content %>
<%= f.submit "Update Post" %>
<% end %>
在上面的代码中,我们使用form_for
方法来生成一个与@post
对象关联的表单。我们使用url: post_path(@post)
指定了表单提交后将要访问的控制器动作,使用method: :patch
指定了表单使用的HTTP方法。
routes.rb
文件中添加以下代码:Rails.application.routes.draw do
resources :posts
end
上面的代码将自动生成与posts
资源相关的路由,包括edit
和update
动作所需的路由。
通过以上步骤,您应该能够解决表单提交后无法更新Ruby on Rails视图的问题。请注意,以上示例代码是基于一般情况,实际应用中可能需要根据具体需求进行适当的调整。