Rails 4验证:我是否确保外键或关联变量本身存在关联?

时间:2015-04-15 21:45:17

标签: ruby-on-rails ruby ruby-on-rails-4

在Rails 4中,确保关联存在的最佳方法是什么? 看起来您可以使用外键或关联变量本身进行测试。 我仍然是Rails的新手,所以这可能是一个愚蠢的问题。 我也在想下面的两种方法都可行。

# method 1:

class Region < ActiveRecord::Base
  # In order to validate associated records whose presence is required, 
  # you must specify the :inverse_of option for the association:
  has_many :flags, inverse_of: :region
end

class Flag < ActiveRecord::Base
  # If you want to be sure that an association is present, 
  # you'll need to test whether the associated object itself is present, 
  # and not the foreign key used to map the association.
  belongs_to :region
  validates :region, :presence => true
end

# method 2:

class Region < ActiveRecord::Base
  has_many :flags
end

class Flag < ActiveRecord::Base
  # Rails 4 Way book: "when you're trying to ensure that an association is present, 
  # pass its foreign key attribute, not the association variable itself"
  validates :region_id, :presence => true
  validate :region_exists

  def region_exists
    errors.add(:region_id, "does not exist") unless Region.exists?(region_id)
  end
end

1 个答案:

答案 0 :(得分:2)

我看了一下validates_associated,认为这将是最好用的。

http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_associated

在validates_associated的注释中是这个花絮:

  

注意:如果没有关联,则此验证不会失败   分配。如果您想确保关联存在   并保证有效,您还需要使用   validates_presence_of。

所以看起来如果您只是在验证了关联被分配后,validates_presence_of应该有效。如果您还想验证关联是否有效,可以同时使用validates_presence_of和validates_associated。