我的form_for提交按钮只能部分工作;数据保存在数据库中,但重定向失败。以下是表格的相关代码:
app/views/orders/new.html.erb
<h1>Menu</h1>
<%= link_to "Back to channel", current_channel_path %>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>Meal</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<% @menu_items.each do |t| %>
<p>
<tr>
<td><%= t.name %></td>
<td><%= number_to_currency(t.price) %></td>
<%= form_for (@order), url: orders_path, remote: true do |f| %>
<td><%= f.number_field :quantity, value: 1, class: "form-control", min: 1 %></td>
<%= f.hidden_field :meal, :value => t.name %>
<%= f.hidden_field :unit_price, :value => t.price %>
<td><%= f.submit "Order", class: "btn btn-primary" %></td>
<% end %>
</tr>
</p>
<% end %>
</tbody>
</div>
以下是routes.rb的代码
Rails.application.routes.draw do
#For Orders
get 'orders' => 'orders#new'
post 'orders' => 'orders#create'
get 'all_orders' => 'orders#show'
resources :users
resources :orders
以下是订单的相关代码
def new
@menu_items = MenuItem.all
@order = Order.new
end
def create
@order = current_channel.orders.build(order_params)
@order.user = current_user
if @order.save
flash.now[:success] = "Order has been recorded!"
redirect_to all_orders_path
else
flash.now[:danger] = "Order was not recorded!"
render 'new'
end
end
我读到提交按钮可能不起作用,因为它嵌套在表中。我已经尝试将表单放在表格之外,但提交仍然没有重定向;然而,提交按钮在两种情况下都会在订单数据库中创建记录。知道为什么会这样吗?在此先感谢您的帮助!
答案 0 :(得分:1)
您需要为索引路径设置路由集,而不是上面列出的路径集。如果您遵循标准的crud惯例,则应使用&#34; resources :orders
&#34;在您的路线文件中,它将生成您需要的post / put / delete / get路由。然后你的重定向就可以了。