Private Rail Association

I have two ActiveRecord models:

class Foo < ActiveRecord::Base
  has_many :bars,:dependent=>:destroy
end

class Bar < ActiveRecord::Base
  belongs_to :foo
end

My project indicates what Barneeds to be linked to Foo, but Foolinked only to Barfor a database dependency - to make sure that when you delete an instance, Fooall related instances Barwill also be deleted. In addition, the code that uses Foodoes not need to know about Bar, and I do not want association methods to be accessible from objects Foo.

I tried declaring privatebefore declaring has_manyin Foo, but it does not work (I think it only works for methods declared directly with def...).

Is there a way to make an association confidential or to achieve database dependency without creating an association Barin Foo?

+5
source share
1 answer

You must place the declaration privateafter the call has_many, as long as the methods for the association are not defined:

class Foo < ActiveRecord::Base
  has_many :bars, :dependent => :destroy
  private :bars, :bars=
end

Foo.first.bars
#=> #<NoMethodError: private method `registrations' called for #<Foo:0x007fc767adca88>>
+11
source

All Articles