我希望能够动态地将表单元素添加到我的订单页面,以便用户可以单击按钮并获得另一个元素来选择产品。然后如何使用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
订单与产品之间的关系是通过订购的产品模型。所以我需要能够添加一个包含所有产品下拉列表和数量文本字段的字段,以便输入他们希望添加到订单中的数量。
非常感谢任何帮助,谢谢。