如何使用has_many关系在父级中存储外键

时间:2014-04-26 08:19:26

标签: ruby-on-rails associations paper-trail-gem

我需要模仿标准的Rails has_many关系,但是使用存储在父级中的外键。

class Product < ActiveRecord::Base
  has_many :questions
end

class Question < ActiveRecord::Base
  belongs_to :product
end

这是因为我使用PaperTrail进行版本控制,当我检索早期版本的@product时,我想看看它与之相关的问题。

到目前为止,我正在考虑创建:

  • 更新序列化问题数组的关联回调 每次添加或删除问题时都会显示ID @ product.questions
  • 读取此数组并将其转换为a的方法 问题集

类似的东西:

class Product < ActiveRecord::Base

  serialize :questions_list, Array

  has_many :questions, :after_add => :update_questions_list, :after_remove => :update_questions_list

  def update_questions_list
    update_column :questions_list, questions.map{|q| q.id}
  end

  def versioned_questions
    questions_list.map{|id| Question.find(id)}
  end

end

然后我在其他方法中专门引用versioned_questions。

但这似乎有些过时,可能是瓶颈的根源。如果可能的话,我想做本地Railsish的事情,在那里我自动获得所有ActiveRecord协会的善意。我可以吗?

顺便说一下,有a StackOverflow question来自它的标题,看起来它回答了我的问题,但它实际上与has_one个关联有关,而不是has_many

1 个答案:

答案 0 :(得分:1)

使用Rails 4对questions_list的PostgresQL数组列类型的支持的最终答案是:

class Product < ActiveRecord::Base

  has_many :questions, :after_add => :add_to_questions_list, :after_remove => :remove_from_questions_list

  def add_to_questions_list(question)
    update_attribute :questions_list, questions_list << question.id
  end

  def remove_from_questions_list(question)
    update_attribute :questions_list, questions_list.reject{|i| i == question.id}
  end

  def versioned_questions
    questions_list.map{|id| Question.find(id)}
  end

end