在我的子分类帐会计应用程序应用程序中,我有一个基金模型
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 < ActiveRecord::Base
belongs_to :agency
belongs_to :fund
has_many :class_sessions
has_many :facilities
validates :agency_id, :fund_id, :name, :gl_account_number, :active, :user_stamp, :account_type, :presence => 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"}
答案 0 :(得分:2)
尝试从GlAccount类中的状态真实验证中删除fund_id。
validates :agency_id, :name, :gl_account_number, :active, :user_stamp, :account_type, :presence => true
并且不要将fund_id添加为隐藏字段,因为你是对的,'fields_for'会自动处理,但这会在验证后发生。
所以你不需要对fund_id进行验证。
<强>更新强>
另外,为了确保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