Search code examples
ruby-on-railsrubyactiverecordhas-manybelongs-to

In Rails, can I set a has_many relation on a model from another model?


Is there any way I can set both halves of a belongs_to/has_many relation in just one of the models? So I want do something like:

class A < ActiveRecord::Base
end

class B < ActiveRecord::Base
  belongs_to :a
  A.has_many :b
end

Obviously this doesn't work (or I would have used it) but I hope it explains what I mean...


Solution

  • I'm not sure why you'd want to, but assuming you have a great reason...

    has_many is just a class method defined in ActiveRecord::Base so calling A.has_many :b should work.

    You might have issues however in development with loading order. If you load up the example you gave and called a = A.new, the class B has never been loaded, so a has no idea that A has many B. In production, where the entire class list is loaded on start, this won't be a problem. In development you can get around it by using a require statement, however, you are then coupling the two files together pretty strongly.

    I haven't tried it, but in theory, that's the only thing I can think of that is preventing your setup above from working.