在Rails 4中我想在设计卖家中创建一个包含产品的订单,我使用gem“cocoon”
class Seller < ActiveRecord::Base
has_many :orders
class Order < ActiveRecord::Base
belongs_to :seller
has_many :products
accepts_nested_attributes_for :products, allow_destroy: true
class Product < ActiveRecord::Base
belongs_to :order
我想在new.html中创建,但卖家不需要登录,我希望它可以通过URL
new.html
<%- model_class = Order -%>
<%= simple_form_for @order, :html => { :class => 'form-horizontal' } do |f| %>
<%= f.simple_fields_for :products do |product| %>
<%= render 'product_fields', :f => product %>
<% end %>
<%= link_to_add_association 'add product', f, :products %>
<%= f.button :submit, :class => 'btn-primary' %>
<% end %>
in product_fields
<%= f.input :name %>
<%= f.input :description %>
<%= link_to_remove_association 'remove product', f %>
def new
current_seller = Seller.find{|person|person.store==params[:store]}
@order = current_seller.orders.new
end
def create
@seller = current_seller
@order = @seller.orders.new(order_create_params)
respond_to do |format|
if @order.save
format.html { redirect_to @order, notice: 'Order was successfully created.' }
format.json { render action: 'show', status: :created, location: @order }
else
format.html { render action: 'new' }
format.json { render json: @order.errors, status: :unprocessable_entity }
end
end
端 像/ orders / new?store = test03
这样的网址def order_create_params
params.require(:order).permit(products_attributes: [:id, :name, :description, :_destroy]).merge(:seller_id => @seller.id)
end
我尝试了很多方法来构建,但现在“删除产品”没有工作,如果我使用Order.new只创建第一个产品可以按顺序保存(显示在开头)并且无法获取seller_id现在将导致nil的未定义方法`orders':我创建时的NilClass
如何定义我的创建动作以创建订单可以链接卖家并添加删除产品可以工作
答案 0 :(得分:5)
product_fields
部分内容需要div
与nested-fields
类包围才能使移除工作正常。