私は 2 つの ActiveRecord モデルを持っていAますB。 A has_many :BとB belongs_to :A。当然、コラムBがありa_idます。
がたくさんありA、新しい を作成するたびに、特定の条件が満たさ Bれる場合に関連付けたいと思います。A
現在、可能性のある を取得し、 1 つを次のようAにリンクしています。B
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
これは臭そうです。2 つのモデルをリンクするより良い方法はありますか? has_manyとのbelongs_to関係を明確にすることで助けになると思いました。私は何かが欠けているに違いない。