Search code examples
ruby-on-railsrubyactiverecordassociationsbelongs-to

Associate two models through belongs_to


I have two ActiveRecord models, A and B. A has_many :B and B belongs_to :A. Naturally, B has an a_id column.

I have a bunch of A's and every time I create a new B, I want to associate it with an A if certain conditions hold.

Currently, I'm retrieving the possible A's and linking one to a B like so:

class B < ActiveRecord::Base

    attr_accessible :a_id
    belongs_to :a

    def link_to_a
        possible_as = A.where(some: conditions)
        self.a = possible_as.find_by_other-foreign-key_id(self.other_id) if possible_as != nil
        # Then I have to perform an operation on the b's a such as:
        self.a.linked_to_b_at = Time.now if self.a != nil
    end
end

This seems smelly. Is there a better way to link the two models? I thought making the has_many and belongs_to relationships explicit would help me. I must be missing something.


Solution

  • If B has a belongs_to relationship with A, then the way you created your B records is incorrect. You got to use the build method to create dependent records.

    For example:

    def create_b_records
     a = A.find(some_id)
     a.build_b(new_record_attributes)
     a.save 
    end
    

    Now, with that, retrieving all B records for a particular set of A records becomes quite straightforward:

    possible_as = A.where(some_condition)
    possible_as.each do |possible_a|
     possible_a.b #Do whatever you want to do with these B records
    end