我是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 %>
提前感谢您的帮助! 斯蒂芬
答案 0 :(得分:0)
belongs_to :client, class_name: "Company", foreign_key: "id"
应该是
belongs_to :client, class_name: "Company", foreign_key: "client_id"
此外,我会更新您的迁移并使该字段不可为空,更好地获得例外而不是保存没有客户的订单