1

我是 Rails 新手,一直在努力解决以下问题。不幸的是,经过数小时的搜索并没有找到解决方案,所以我很乐意得到您的意见。

在创建订单时,我尝试创建一个客户端(作为父级)和订单项(作为子级)。后者工作正常。但是,在保存订单时,订单和客户都存储在数据库中,只是 *client_id* 没有传递到订单记录。

下面是我的代码:

公司模式

class Company < ActiveRecord::Base

  has_many :orders,     foreign_key: "client_id"
  accepts_nested_attributes_for :orders

  validates :name, 
            :presence => true,
            :uniqueness => { :case_sensitive => false } 

  validates_associated  :users,
                        :orders

  attr_accessible :name, 
                  :account, 
                  :users_attributes,
                  :orders_attributes,  
                  :company_id
end

订单模式

class Order < ActiveRecord::Base

    has_many :order_items
    accepts_nested_attributes_for   :order_items

    belongs_to  :client, class_name: "Company",
                                    foreign_key: "id"
    accepts_nested_attributes_for   :client

    attr_accessible :order_items_attributes,
                    :order_number,
                    :client_attributes,
                    :client_id

    validates_associated    :order_items

    validates_presence_of   :order_number
                            :client_id
end

订单控制器

  def create
    @order = @client.orders.build(params:[orders])
    puts @order.to_yaml

    respond_to do |format|

      if @order.save!
        format.html { redirect_to @order, notice: 'Order was successfully created.' }
        format.json { render json: @order, status: :created, location: @order }
      else
        format.html { render action: "new" }
        format.json { render json: @order.errors, status: :unprocessable_entity }
      end
    end
  end

新订单

<%= simple_form_for @order, :html => { :class => 'form-horizontal' } do |f| %>
    <%= render 'shared/error_messages', :object => @order %> 
  <div class = "span3">
    <%= f.simple_fields_for :client do |client_builder| %>
      <%= client_builder.input  :name, 
                                :label => 'Client' %>
    <% end %>

    <%= f.input :order_number %>
    <%= f.simple_fields_for :order_items do |items_builder| %>
        <%= items_builder.input :reference_number %>
        <%= items_builder.input :item_description %>
    <% end %>

    <%= f.button  :submit,
                  :class => 'btn'%>
    <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                              orders_path, :class => 'btn' %>
  </div>
<% end %>

提前感谢您的帮助!斯特凡

4

1 回答 1

0
belongs_to  :client, class_name: "Company", foreign_key: "id"

应该

belongs_to  :client, class_name: "Company", foreign_key: "client_id"

此外,我会更新您的迁移并使该字段不可为空,比在没有客户端的情况下保存订单更好地获得异常

于 2013-11-09T15:47:21.557 回答