向现有客户添加订单

时间:2015-11-18 12:14:58

标签: ruby-on-rails ruby-on-rails-4 activerecord associations

Hello其他程序员,我正在构建一个应用程序,我可以向现有客户添加订单。到目前为止,我可以添加一个客户。但是一个星期以来我一直在向客户添加订单。我是rails的新手(现在一个月)。我已关联客户和ID模型。这是我的代码。

更新: customer_id是订单表中的外键

  

客户控制器

class CustomerController < ApplicationController
  def index
    @customers = Customer.sorted
  end

  def new
     @customers = Customer.new
    #hij creert een nieuwe subject
  end

  def create
     #Instantiate a new object using form paramters
    @customer = Customer.new(customer_params)
    #Save the object
    if @customer.save
    #If save succeeds, redirect to the inex acton
    flash[:notice] = "Subject created successfully"
    redirect_to(:action => 'index')
    else
    #If save fails, redisplay the form so user can fix problems
    render('new') #het zit in de new.html template
    end
  end


  def show
    @customers = Customer.find(params[:id])

  end

  def edit
    @customer = Customer.find(params[:id])
  end

  def delete
     @customer = Customer.find(params[:id])
  end

  def destroy
    customer = Customer.find(params[:id]).destroy #deze is zonder @ omdat het geen template rendert
    flash[:notice] = "Subject '#{customer.first_name}' destroyed successfully"
    redirect_to(:action => 'index')
  end

  private
  def customer_params
    params.require(:customer).permit(:first_name, :last_name)
  end
end
  

订单控制器

class OrderController < ApplicationController
  def index
     @order = Order.find(params[:customer_id])
  end

  def new
     @orders = Order.new
  end

 def create
  @order = Order.new(order_params)
  if @order.save
    flash[:notice] = "Subject created successfully"
    redirect_to(:action => 'index')
  else
    render 'customers/show'
  end
end

  end

  def show
   @order = Order.find(params[:customer_id]) 
  end

  def edit
  end

  def delete
  end

  private
  def order_params
    params.require(:order).permit(:customer_id, :pakket, :verstuurt)
  end
  

客户展示视图

<% if !flash[:notice].blank? %> 
    <div class="notice">
        <%= flash[:notice] %>
<% end %>

<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>

<div class="subjects show">
    <h2><%=@customers.first_name %></h2>


    <%= link_to("View Pages", {:controller => 'order', :customer_id => @customers.id}, :class => 'action show') %>
    <%= link_to("Edit", {:action => 'edit', :id => @customers.id}, :class => 'action edit') %>
    <%= link_to("Delete",{:action => 'delete', :id => @customers.id}, :class => 'action delete') %>
    <%= link_to("Create",{:controller => 'order/create', :customer_id => @customers.id}, :class => 'action create') %>
</div>
  

为现有客户页面创建新订单

<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>

<div class="subject new">
    <h2>Create Subject</h2>

    <%= form_for @order do |f| %>

    <table summary="subject form fields">
        <tr>
            <th>Package</th>
            <td><%= f.text_field(:pakket) %></td>
        </tr>
        <tr>
            <th>Sent</th>
            <td><%= f.text_field(:verstuurt) %></td>
        </tr>

    </table>

    <div class="form-buttons">
        <%= submit_tag("Create Subject") %>
    </div>

    <% end %>
</div>
  

客户模式

class Customer < ActiveRecord::Base
    has_many :orders
    accepts_nested_attributes_for :orders

    scope :sorted, lambda { order("first_name ASC") }
    scope :visible, lambda { where(:visible => true) }
    scope :invisible, lambda { where(:visible => false) }
    scope :newest_first, lambda { order("customers.created_at DESC")}
    scope :search, lambda {|query|
    }
end
  

订单型号

class Order&lt;的ActiveRecord ::基

    belongs_to :customer

    accepts_nested_attributes_for :customer

    scope :visible, lambda { where(:visible => true) }
    scope :invisible, lambda { where(:visible => false) }
    scope :sorted, lambda { sorted("orders") }
    scope :newest_first, lambda { order("orders.created_at DESC")}
    scope :search, lambda {|query|
        where(["name LIKE ?", "%#{query}%"])}
end
  

错误

ActionController::ParameterMissing in OrderController#create
param is missing or the value is empty: order

Extracted source (around line #34):
32
33
34
35
36

  private
  def order_params
    params.require(:order).permit(:customer_id, :pakket, :verstuurt)
  end
  

服务器日志

Started GET "/order/create?customer_id=9" for ::1 at 2015-11-18 14:47:40 +0100
Processing by OrderController#create as HTML
  Parameters: {"customer_id"=>"9"}
  Customer Load (0.1ms)  SELECT  "customers".* FROM "customers" WHERE "customers"."id" = ? LIMIT 1  [["id", 9]]
Completed 400 Bad Request in 2ms (ActiveRecord: 0.1ms)

ActionController::ParameterMissing (param is missing or the value is empty: order):
  app/controllers/order_controller.rb:33:in `order_params'
  app/controllers/order_controller.rb:14:in `create'


  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_source.erb (4.1ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.0ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (56.6ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb (0.4ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.4ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.4ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.4ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (49.7ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.4ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.5ms)
  Rendered /Users/cecil/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (111.1ms)

4 个答案:

答案 0 :(得分:1)

如果您希望创建已与客户相关的订单,则需要使用嵌套路由:

#routes.rb

resources :customers do
  resources :orders
end

通过这种方式,您可以使用/customers/:customer_id/orders/new

为特定客户创建新订单

然后在OrderController中使用以下内容:

def new
  @customer = Customer.find(params[:customer_id])
  @order = @customer.orders.build()
end

这样,订单已经与客户相关,并且将填充表单中的customer_id字段。

编辑但这仍然允许无限制地为每位客户创建订单。当我听到秩序&amp;客户可能需要身份验证和授权,因此请查看Devise,以便您可以让某个人订购某些东西。当您打算使用它时,您不需要嵌套路由,因为customer_id将在保存之前设置。

答案 1 :(得分:1)

好的,我不确定你是如何尝试使用你的控制器......但是让我们重构你的OrdersController如下:

class OrdersController < ApplicationController
  def index
     @orders = <whatever you want it to be> # Note that I used the plural form of @orders, not @order
  end

  def new
    customer = Customer.find(params[:customer_id])
    @order = customer.order.new
  end

  def create
    @order = Order.new(order_params)
    if @order.save
      flash[:notice] = "Subject created successfully"
      redirect_to(:action => 'index')
    else
      render 'customers/show'
    end
  end

  def show
    @order = Order.find(params[:customer_id]) 
  end

  def edit
  end

  def delete
  end

  private
  def order_params
    params.require(:order).permit(:customer_id, :pakket, :verstuurt)
  end
end

然后,以您的订单形式:

<%= form_for @order do |f| %>
  <table summary="subject form fields">
    <tr>
      <th>Package</th>
      <td><%= f.text_field(:pakket) %></td>
    </tr>
    <tr>
    <th>Sent</th>
      <td><%= f.text_field(:verstuurt) %></td>
    </tr>
  </table>

  <div class="form-buttons">
    <%= f.submit %>
  </div>
<% end %>

这应该适合你。

答案 2 :(得分:1)

  

我是rails的新手(现在一个月)。

坚持下去 - 在开始之前至少需要3个应用程序&#34;得到它&#34;。到目前为止,你做得非常好!!

除了其他答案之外,还有一个更直接的问题:

param is missing or the value is empty: order

这意味着您将参数传递给控制器​​,而这些参数未按您的需要进行格式化。这可能会暗示您的表单或控制器代码不正确。

-

第一个停靠点在这里:

<div class="form-buttons">
    <%= submit_tag("Create Subject") %>
</div>

需要<%= f.submit %>

这应解决立即参数错误。

-

关于如何将ordercustomer相关联的更广泛问题,您需要了解nested resources

#config/routes.rb
resources :customers do
   resources :orders #-> url.com/customers/:customer_id/orders/:id
end

这将允许您执行以下操作:

#app/controllers/orders_controller.rb
class OrdersController < ApplicationController 
   def new
      @customer = Customer.find params[:customer_id]
      @order = @customer.orders.new
   end

   def create
      @customer = Customer.find params[:customer_id]
      @order = @customer.orders.new order_params
      @order.save
   end

   private

   def order_params
      params.require(:order).permit(:pakket, :verstuurt)
   end
end

这会自动为您设置foreign_key;允许你打电话:

#app/views/orders/new.html.erb
<%= form_for @order do |f| %>
   <%= f.text_field(:pakket) %>
   <%= f.text_field(:verstuurt) %>
   <%= f.submit %>
<% end %>

在极少数情况下,Rails指南与示例相匹配,here's how your foreign key should look

enter image description here

答案 3 :(得分:0)

将您的/ orders / new更改为:

    <%= form_for @order do |f| %>
      <table summary="subject form fields">
        <tr>
          <th>Package</th>
          <td><%= f.text_field(:pakket) %></td>
        </tr>
        <tr>
        <th>Sent</th>
          <td><%= f.text_field(:verstuurt) %></td>
      <%= f.hidden_field(:customer_id) %>
        </tr>
      </table>

  <div class="form-buttons">
    <%= f.submit %>
  </div>
<% end %>