0

I have set up my first HABTM tables (hosts and owners) with a join table (hosts_owners). My tests seem to be working fine and similarly so do the web pages.

So, my next question is how to insert new data and their respective relationships (ie., join table information). Since I expect there will be two primary ways of inserting new data:

  1. Programmatically, where the content is retrieved from other sources and saved into the tables
  2. Manually, users will use the web pages to add new entries.

So, for each of the above, what is the "rails" way of ensuring that each time a host is added at least one owner is also added? (And vice versa.) All of the books and articles I found seem to stop at the point of creating the tables and models.

Seki
  • 11,135
  • 7
  • 46
  • 70
moosya
  • 1

1 Answers1

0

use a validation callback. It is similar to a database trigger, but belongs to your rails models.

eg. (not sure if this works, must try):

class Host < ActiveRecord::Base
  validates :has_at_least_one_owner?

  def has_at_least_one_owner?
    owners.any?
  end
end 

PS: maybe you could use validates_presence_of instead, don't know if it works with HABTM though

m_x
  • 12,357
  • 7
  • 46
  • 60