0
我期望能夠動態添加表單元素到我的訂單頁面,以便用戶可以單擊按鈕並給出另一個元素來選擇產品。然後如何用Rails來處理。這裏是我當前的文件:Rails:動態添加產品到訂單
訂貨型號:
class Order < ActiveRecord::Base
attr_accessible :client_id, :order_total, :delivery_date
has_many :orderedproducts
has_many :products, through: :orderedproducts
has_one :client
before_save :generate_total
def generate_total
self.order_total = self.products.map(&:product_price).sum
end
end
訂單控制器:
class OrdersController < ApplicationController
def view
@orders = Order.all
end
def new
@order = Order.new
end
end
新秩序觀:
<% if current_user %>
<div id="dashboard">
<div id="logo"></div>
<table id="go_back_link_container">
<tr>
<td>
<div class="go_back_link">
<%= link_to "<- Go Back", root_url %>
</div>
</td>
<td>
<div id="user_display">
Logged in as <%= current_user.email %>.
<%= link_to "Log out", log_out_path %>
</div>
</td>
</tr>
</table>
<%= form_for @order do |f| %>
<% if @order.errors.any? %>
<div class="error_messages">
<% for message in @order.errors.full_messages %>
* <%= message %> <br>
<% end %>
</div>
<% end %>
<p>
<%= f.label 'Select The Client' %><br />
<%= select :client, :client, Client.all().collect { |c| [ (c.firstname + " " + c.surname), c.id ] } %>
</p>
<p>
<%= f.label 'Select The Client' %><br />
<%= f.fields_for :products do |builder| %>
<%= render '', f: builder %>
<% end %>
</p>
<p class="button"><%= f.submit %></p>
<% end %>
<% flash.each do |name, msg| %>
<%= content_tag :div, "* " + msg, :id => "flash_#{name}" %><br />
<% end %>
<div id="copyright-notice"><div id="copyright_border">Copyright © Conner McCabe, all rights reserved.</div></div>
</div>
<% else %>
<script type="text/javascript">
window.location="<%= root_url %>"
</script>
<% end %>
訂購的產品型號:
class Orderedproduct < ActiveRecord::Base
attr_accessible :order_id, :product_id, :quantity_ordered
belongs_to :order
belongs_to :product
end
產品型號:
class Product < ActiveRecord::Base
#This line makes these elements accessible outside of the class.
attr_accessible :product_name, :product_price, :product_quantity, :product_supplier
has_many :orderedproducts
has_many :orders, through: :orderedproducts
#These attributes ensure that the data entered for each element is valid and present.
validates_presence_of :product_name
validates_presence_of :product_price
validates_numericality_of :product_price
validates_presence_of :product_quantity
validates_numericality_of :product_quantity
validates_presence_of :product_supplier
end
訂單和產品之間的關係是通過訂購的產品型號。所以我需要能夠添加一個包含所有產品下拉列表和數量文本字段的字段,以便我可以輸入他們希望添加到訂單中的數量。
任何幫助非常感謝,謝謝。