Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private association in rails

I have two ActiveRecord models:

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

class Bar < ActiveRecord::Base
  belongs_to :foo
end

My design dictates that Bar needs to be associated to Foo, but Foo is only associated to Bar for the database dependency - to make sure that when an instance of Foo is deleted, all associated instances of Bar will also be deleted. Aside from that, code that uses Foo should not know about Bar, and I don't want the association methods to be accessible from the Foo objects.

I've tried declaring private before the has_many declaration in Foo, but it doesn't work(I guess it only works for methods declared directly with def...).

Is there any way to make the association private, or to achieve the database dependency without creating a Bar association in Foo?

like image 573
Idan Arye Avatar asked Aug 26 '12 16:08

Idan Arye


1 Answers

You must put the private declaration after you call has_many, as it is not till then that the methods for the association are 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>>
like image 62
Andrew Marshall Avatar answered Sep 19 '22 20:09

Andrew Marshall