使用fields_for的Rails错误消息

在我的子分类帐会计应用程序应用程序中,我有一个基金模型

class Fund < ActiveRecord::Base belongs_to :agency has_many :gl_accounts accepts_nested_attributes_for :gl_accounts attr_accessible :name, :agency_id, :fund, :user_stamp, :active attr_accessible :gl_accounts_attributes 

和gl_accounts模型

 class GlAccount  true validates_uniqueness_of :account_type, :scope => :fund_id, :if => :unique_account_type attr_accessible :agency_id, :fund_id, :name, :gl_account_number, :active, :user_stamp, :account_type def unique_account_type [3,4,6,7,8].include? account_type end 

当创建新基金时,必须同时创建5个gl_accounts,因此当为基金创建新记录时,我使用fields_for在gl_account模型中创建5个新记录。 这一切似乎都工作正常,直到我提交表格,我得到一个错误说“Gl账户基金不能空白。”

gl_accounts模型中没有“fund”属性。 我认为也许rails正在放弃“_id”部分(因为有一个fund_id外键字段)但我理解使用嵌套模型和fields_for自动在fund_id字段中添加适当的值(gl_account的外键)模型)。 但即使我在表单中添加一个带有fund_id值的隐藏字段,我仍然会得到错误,说“基金”不能为空。

那么,也许rails试图告诉我我还有别的错吗?

以下是参数:

 {"utf8"=>"✓", "authenticity_token"=>"MNWLFOnLOE+ZRsUf9mogf2cq/TeQ+mxtrdaVu3bEgpc=", "fund"=>{"agency_id"=>"1", "user_stamp"=>"6", "name"=>"Junk", "fund"=>"44", "active"=>"1", "gl_accounts_attributes"=>{"0"=>{"agency_id"=>"1", "user_stamp"=>"6", "account_type"=>"6", "name"=>"Cash Account", "active"=>"1", "fund_id"=>"1", "gl_account_number"=>"44-498-965-789"}, "1"=>{"agency_id"=>"1", "user_stamp"=>"6", "account_type"=>"7", "name"=>"Credit Card Account", "active"=>"1", "fund_id"=>"1", "gl_account_number"=>"44-498-965-163"}, "2"=>{"agency_id"=>"1", "user_stamp"=>"6", "account_type"=>"3", "name"=>"Customer Account Balances", "active"=>"1", "fund_id"=>"1", "gl_account_number"=>"44-498-965-254"}, "3"=>{"agency_id"=>"1", "user_stamp"=>"6", "account_type"=>"8", "name"=>"Refunds Pending Account", "active"=>"1", "fund_id"=>"1", "gl_account_number"=>"44-498-965-456"}, "4"=>{"agency_id"=>"1", "user_stamp"=>"6", "account_type"=>"4", "name"=>"Deferred Revenue Account", "active"=>"1", "fund_id"=>"1", "gl_account_number"=>"44-498-965-159"}}}, "commit"=>"Add New Fund"} 

尝试从GlAccount类中的存在真实validation中删除fund_id。

 validates :agency_id, :name, :gl_account_number, :active, :user_stamp, :account_type, :presence => true 

并且不要将fund_id添加为隐藏字段,因为,你是对的,’fields_for’将自动处理,但这将在validation后发生。

所以你不需要fund_id来validation存在。

更新

另外,为了确保fund_id永远不为null,您可以在数据库表中放置约束。 使用以下代码创建迁移。

 change_column :gl_accounts, :fund_id, :integer, :null => false 

更新2

为确保资金存在,您需要检查基金的存在而不是fund_id。

 validates :fund, :presence => true 

为此,您需要声明与“inverse_of”的关联,如下所示。

 class Fund < ActiveRecord::Base has_many :gl_accounts, inverse_of: :fund accepts_nested_attributes_for :gl_accounts end class GlAccount < ActiveRecord::Base belongs_to :fund, inverse_of: :gl_accounts validates_presence_of :fund end 

有关详细信息,请参阅本指南。 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#label-Validating+the+presence+of+a+parent+model