0
votes

my form_for submit button only works partially; the data is saved in the database but the redirection fails. Here are the relevant codes for the form:

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>

Here are the codes for 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 

Here are the relevant codes for 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

I read that the submit button may not work as it is nested in the table. I have tried putting the form outside of the table but the submit still does not redirect; the submit button however creates the record in the orders database in both cases. Any idea why this is the case? Thanks in advance for any help!

1
What do you mean by redirection fails?Pavan
you are making ajax request. you need create.js.erb file not redirection.Athar
The error message would help to diagnosenextstep
@Pavan by redirection fails, i mean that i dont get redirected to the correct page after i click the submit buttom but the data is recorded in the database.chocomousse
To which you want to be redirected to?Pavan

1 Answers

1
votes

You need a route set for the index path which isn't listed above. If you're following standard crud conventions you should just use "resources :orders" in your routes files which will generate the post/put/delete/get routing you need. Then your redirection will work.