Ruby on rails 5验证失败,属于关系存在

时间:2017-10-31 12:50:10

标签: ruby-on-rails ruby

我有两个不同的关联到同一个表,如下面我的模型(Grant)中定义的那样:

belongs_to :taxes_period, class_name: 'Period'
belongs_to :insurance_period, class_name: 'Period'

期间是一个包含值MonthlyQuarterlyYearly的表格。所以在我的授权表单更新或创建中,我在后端(@grant.errors)得到验证错误:

 @details={:taxes_period=>[{:error=>:blank}]},
 @messages={:taxes_period=>["must exist"]}>

但当我检查对象是否存在taxes_period_id时,它就在那里,并提供相关的调试细节:

@grant.taxes_period_id
=> 2
[7] pry(#<GrantsController>)> Period.find(@grant.taxes_period_id)
  Period Load (1.0ms)  SELECT  "periods".* FROM "periods" WHERE "periods"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
=> #<Period:0x007f8571220e18 id: 2, name: "Monthly">
[8] pry(#<GrantsController>)> @grant.valid?
  Period Load (2.3ms)  SELECT  "periods".* FROM "periods" ORDER BY "periods"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Period Load (0.6ms)  SELECT  "periods".* FROM "periods" WHERE "periods"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
=> false

为什么我无法保存此对象?这是怎么回事?

1 个答案:

答案 0 :(得分:0)

长答案简短,关系名称不正确,应该命名为:

tax_period_id代替taxes_period_id

我已经没有了,我认为rails确实强制执行约定优于配置。一切都从适当的命名开始,我猜,这真的是最后的手段。