我需要模仿标准的 Railshas_many
关系,但外键存储在父级中。
class Product < ActiveRecord::Base
has_many :questions
end
class Question < ActiveRecord::Base
belongs_to :product
end
这是因为我使用PaperTrail进行版本控制,当我检索 @product 的早期版本时,我想查看它与哪些问题相关联。
到目前为止,我正在考虑创建:
- 每次在@product.questions 中添加或删除问题时,关联回调会更新问题 ID 的序列化数组
- 读取此数组并将其转换为问题集合的方法
就像是:
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 Association 的好处。我可以吗?
顺便说一句,有一个 StackOverflow 问题,从它的标题来看,它似乎回答了我的问题,但它实际上与has_one
关联有关,而不是has_many
.