validates_presence_of和未保存的关联

时间:2012-05-25 12:07:31

标签: ruby-on-rails ruby-on-rails-3 validation activerecord

使用以下代码(Rails 3.0.10):

User < AR
  has_many :providers

Provider < AR
  belongs_to :user
  validates_presence_of :user

user = User.new
user.providers.build
# so both models not yet saved but associated with each other

user.valid?
=> false

user.errors
=> {:providers=>["is invalid"]}

user.providers.first.errors
=> {:user_id=>["can't be blank"]}

为什么提供商无法看到它有一个尚未保存的关联用户模型?或者换句话说 - 我如何处理它以便验证仍然存在?或者也许我做错了什么?

请注意,我正在寻找一个干净的解决方案,因此建议在Provider模型中进行验证前回调,将User模型保存到数据库是不行的。

1 个答案:

答案 0 :(得分:4)

使用:inverse_of

class User < ActiveRecord::Base
  has_many :providers, :inverse_of => :user
end

class Provider < ActiveRecord::Base
  belongs_to :user, :inverse_of => :providers
  validates :user, :presence => true
end