通过belongs_to关联两个模型

时间:2012-12-10 07:23:02

标签: ruby-on-rails ruby activerecord associations belongs-to

我有两个ActiveRecord模型,ABA has_many :BB belongs_to :A。当然,B有一个a_id列。

我有一堆A个,每次创建新的B时,如果某些条件成立,我想将其与A相关联。

目前,我正在检索可能的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

这看起来很臭。有没有更好的方法来链接这两个模型?我认为明确has_manybelongs_to关系可以帮助我。我一定错过了什么。

2 个答案:

答案 0 :(得分:1)

添加一个进行关联的after_create过滤器

class B < ActiveRecord::Base

  attr_accessible :a_id
  belongs_to :a
  after_create :link_to_a

  def link_to_a
    update_attribute(:a_id, find_a )
  end

  def find_a #returns id of a
    your logic to find a
    ...
   end
end

然后像往常一样创建模型B. 看看这个,它有完整的例子来管理这种类型的关联。

http://guides.rubyonrails.org/getting_started.html#adding-a-second-model

答案 1 :(得分:1)

如果B与A有belongs_to关系,那么您创建B记录的方式不正确。您必须使用build方法创建相关记录。

例如:

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

现在,通过这种方式,检索特定A组记录的所有B记录变得非常简单:

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