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?
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>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With