rails accepts_nested_attributes_for - 错误:Mysql2 ::错误:未知列'优惠'。在'where子句'

时间:2012-10-17 20:16:21

标签: ruby-on-rails-3 forms nested-attributes

代码是:

class Client < ActiveRecord::Base
  ...
  has_one :offer, :dependent => :destroy
  accepts_nested_attributes_for :offer
  ...
end

class Offer < ActiveRecord::Base
  ...
  belongs_to :client
  ...
end


<%= simple_form_for [:admin, @client], :html=>  {:multipart => true } do |f| %>
..some input fields
<%= f.simple_fields_for :offer, @client.new_record? ? Offer.new : ""  do |o| %>
..some input fields

这适用于新条目,但不会更新。

  

错误:Mysql2 ::错误:未知列'优惠'。在'where子句'中:DELETE FROM offers WHERE offers。``= 718

当我将客户端模型更改为:

accepts_nested_attributes_for :offer, :reject_if => lambda {|a| a[:name].blank?}

错误消息消失了,它更新了客户端表,但没有更新商品表。

这是有效的:

  has_one :offer, :dependent => :destroy
  accepts_nested_attributes_for :offer, allow_destroy: true

  belongs_to :client

  <%= f.simple_fields_for :offer, @client.new_record? ? Offer.new : @client.offer  do |o| %>

1 个答案:

答案 0 :(得分:1)

首先,它似乎是合乎逻辑的,它不适用于更新,就像你正在做的那样:

<%= f.simple_fields_for :offer, @client.new_record? ? Offer.new : ""  do |o| %>

简单字段将尝试为&#34;&#34;创建字段,而它应该使用商品对象。 您可以解决这个问题(可能有更好的方法,这只是一个解决方案,而不是解决方案)

<%= f.simple_fields_for :offer, @client.offer.new_record? ? Offer.new : @client.offer  do |o| %>

编辑:我认为如果它不存在,那么仅建立报价会更好,所以这就是它的样子:

<% @client.build_offer if @client.offer.new_record? %>
<%= f.simple_fields_for :offer do |o| %>