开发者

Rails many-to-many foreign key validation?

开发者 https://www.devze.com 2023-04-07 01:09 出处:网络
Newbie question. I would like to add a validation step to my joint table model to make sure that an object of that type cannot be created without the two tables being joined containing the rows being

Newbie question. I would like to add a validation step to my joint table model to make sure that an object of that type cannot be created without the two tables being joined containing the rows being references. For example:

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

How do I make sure Appearance cann开发者_StackOverflow社区ot be created if Dancer and Movie rows don't exist?

Thanks folks!

Edit: to answer number's proposal below:

I haven't had much luck with that unfortunately. By playing with the console (after reload) I get something like:

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

whereas I'd expect the response to be false since I just nuked the Movie row.


You probably want to validate for presence, something like:

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

Edit: Added inverse_of to the associations, which may keep an appearance from being valid if their dancer or movie is destroyed after being loaded. (Or it may not. I didn't test this, but a purpose of inverse_of is to provide better in-memory association handling).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号