在 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 这样结束 URL
def order_create_params
params.require(:order).permit(products_attributes: [:id, :name, :description, :_destroy]).merge(:seller_id => @seller.id)
end
我尝试了很多构建方法,但现在“删除产品”不起作用,如果我使用 Order.new 仅创建第一个产品可以按顺序保存(显示在开头)并且现在无法获取eller_id当我创建时将导致 nil:NilClass 的未定义方法“订单”
我如何定义我的创建动作来创建订单可以链接卖家并添加删除产品可以工作