当我尝试使用form_with
和指向现有控制器操作的自定义URL提交发布请求时,视图不会呈现。
我正在尝试遵循一个教程,该教程显示ROR中的form_for
和form_tag
之间的区别,但是尝试使用form_with
,因为前者将不推荐使用。使用form_tag
一切正常。
表单帮助者的Rails Guides仅显示form_for
和form_tag
。
ROR API docs确实显示了form_with
的一些示例,但是我并没有连接点。
<!-- index.html.erb -->
<%= form_with(url: create_users_path) do |f| %>
<%= f.text_field :name, placeholder: "Your Name" %>
<%= f.number_field :age, placeholder: "Your Age" %>
<%= f.submit "Create Profile" %>
<% end %>
和
# routes.rb
get 'users' => 'welcome#users'
post 'create_users' => 'welcome#users'
和
# welcome_controller.rb
def users
if params[:name] != nil
user = User.create(name: params[:name], age: params[:age])
end
@users = User.all
end
和
<!--users.html.erb-->
<table border="2">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.age %></td>
</tr>
<% end %>
</table>
<br>
<%= link_to "Return to Index", root_path %>
我的用户表使用表单中发送的数据进行更新,但是由于index.html.erb
的活动记录调用是,所以我留在了我的users.html.erb
视图上,而不是期望的.create
在users
操作中。
这是我来自POST
请求的服务器日志,其中welcome/users.html.erb
被渲染(浏览器未更新。)GET
将在浏览器中渲染页面
Started POST "/create_users" for 127.0.0.1 at 2018-08-05 22:18:26 -0400
Processing by WelcomeController#users as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"upoeRgVioYXs+Z+vsyBdg4CnXrSTOMCzPFXSHUKT2IlrVMDtvnf8UD7yJkPMYw0zkwihmPvY3Yq0BlG7RFsIIQ==", "name"=>"testy testerson", "age"=>"28", "commit"=>"Create Profile"}
(0.1ms) begin transaction
SQL (2.4ms) INSERT INTO "users" ("name", "age", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "testy testerson"], ["age", 28], ["created_at", "2018-08-06 02:18:26.466212"], ["updated_at", "2018-08-06 02:18:26.466212"]]
(3.2ms) commit transaction
Rendering welcome/users.html.erb within layouts/application
User Load (0.2ms) SELECT "users".* FROM "users"
Rendered welcome/users.html.erb within layouts/application (4.3ms)
Completed 200 OK in 147ms (Views: 56.8ms | ActiveRecord: 6.7ms)
Started GET "/users" for 127.0.0.1 at 2018-08-05 22:19:19 -0400
Processing by WelcomeController#users as HTML
Rendering welcome/users.html.erb within layouts/application
User Load (0.3ms) SELECT "users".* FROM "users"
Rendered welcome/users.html.erb within layouts/application (2.3ms)
Completed 200 OK in 60ms (Views: 51.1ms | ActiveRecord: 0.3ms)
我非常确定,在同一动作中进行创建和显示不是最佳实践……只是试图更好地理解rails。我对路线/控制器/视图关系缺少什么?
我正在使用Rails versrion 5.1.6