Rails多对多外键验证?

时间:2011-09-24 23:07:24

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

新手问题。我想在我的联合表模型中添加一个验证步骤,以确保在没有连接的两个表包含作为引用的行的情况下,无法创建该类型的对象。例如:

class Appearance < ActiveRecord::Base
  belongs_to :dancer
  belongs_to :movie
end

class Dancer < ActiveRecord::Base
  has_many :appearances, :dependent => :destroy, :foreign_key => 'dancer_id'
  has_many :movies, :through => :appearances
end

class Movie < ActiveRecord::Base
  has_many :appearances, :dependent => :destroy, :foreign_key => 'movie_id'
  has_many :dancers, :through => :appearances
end

如果舞者和电影行不存在,如何确保无法创建外观?

谢谢大家!

编辑:在下面回答号码的建议:

不幸的是,我没有太多运气。通过使用控制台(重新加载后)我得到类似的东西:

appearance = Appearance.new(:dancer_id = Dancer.all.first.id, :movie_id => Movie.all.first.id)
Movie.all.first.destroy
appearance.valid?
=> true

然而我希望这个回答是假的,因为我刚刚修改了电影行。

1 个答案:

答案 0 :(得分:0)

您可能希望验证状态,例如:

class Appearance
  belongs_to :movie, :inverse_of => :appearances
  belongs_to :dancer, :inverse_of => :appearances

  validates :movie, :dancer, :presence => true
end

class Movie
  has_many :appearances, :inverse_of => :movie, ...
end

class Dancer
  has_many :appearances, :inverse_of => :dancer, ...
end

修改:向关联添加了inverse_of,如果appearancedancer在加载后被销毁,可能会使movie无效。 (或者它可能没有。我没有对此进行测试,但inverse_of的目的是提供更好的内存中关联处理。)