item id没有保存到order_items表中,我在表单中使用了以下特定代码:
<%= f.association :items, collection: Item.all, label_method: :name, value_method: :id, placeholder: 'Item Name', input_html: { id: 'item-select2' } %>
我是否遗漏了一些东西来保存所选项目的id。提交表单后不会出现错误。
#模型
#models/order.html.erb
class Order < ActiveRecord::Base
belongs_to :user
belongs_to :client
has_many :order_items
has_many :items, :through => :order_items
accepts_nested_attributes_for :order_items, :allow_destroy => true
end
#models/item.html.erb
class Item < ActiveRecord::Base
has_many :order_items
has_many :orders, :through => :order_items
end
#models/order_item.html.erb
class OrderItem < ActiveRecord::Base
belongs_to :item
belongs_to :order
end#Contoller
#controllers/orders_controller.rb snippet
def new
@order = Order.new
@order.order_items.build
end
def edit
end
def create
@order = Order.new(order_params)
@order.user_id = current_user.id
@order.status = TRUE
respond_to do |format|
if @order.save
format.html { redirect_to @order, notice: 'Order was successfully created.' }
format.json { render :show, status: :created, location: @order }
else
format.html { render :new }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
end#视图
#view/orders/_form.html.erb
<% do_ajax = false unless (defined? do_ajax) %>
<%= compact_form_for(@order, remote: do_ajax) do |f| %>
<%= f.error_notification %>
<div class="row form-inputs">
<div class="col-md-3">
<%= f.association :client, collection: Client.all, label_method: :name, value_method: :id, prompt: "Client Name", required: true, input_html: { id: 'client-select2' } %>
</div>
</div>
<br>
<div class="row form-inputs">
<div class="col-md-12">
<div id="items">
<%= render 'orders/items_form', :f => f %>
</div>
<div class="btn btn-success">
<i class="icon-plus"></i></div>
</div>
</div>
<div class="col-sm-12">
<div class="text-right text-contrast subtotal">
</div>
</div>
<br>
<%= f.input :memo, placeholder: 'Notes' %>
<br>
<div class="row">
<div class="col-md-6">
<%= f.button :submit %>
</div>
</div>
<% end %>
#view/orders/_items_form.html.erb
<table class='table table-striped table-hover table-bordered'>
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td id="item" class="col-md-3">
<%= f.association :items, collection: Item.all, label_method: :name, value_method: :id, placeholder: 'Item Name', input_html: { id: 'item-select2' } %>
</td>
<td id="price"></td>
<%= f.simple_fields_for :order_items do |o| %>
<td class="col-md-2"><%= o.input :quantity, input_html: { id: 'quantity' } %></td>
<td id="total" class="col-md-1"></td>
<% end %>
</tr>
</tbody>
</table>附带注意事项和其他问题:我还没有实现到affect the total price的数量。我还没有实现一种添加多个item line的方法。
发布于 2014-06-09 21:41:07
添加
<%= o.input :item_id, collection: Item.all, label_method: :name, value_method: :id, prompt: 'Name', input_html: { id: 'item-select2' } %>
至
<%= f.simple_fields_for :order_items do |o| %>
解决了问题。
https://stackoverflow.com/questions/24128798
复制相似问题