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.
If B has a belongs_to relationship with A, then the way you created your B records is incorrect. You got to use the
buildmethod to create dependent records.For example:
Now, with that, retrieving all B records for a particular set of A records becomes quite straightforward: