新手问题 [已解决] 关于多表关联的问题求助

karrra · November 04, 2015 · Last by karrra replied at November 04, 2015 · 1866 hits

业务需求是有一个 tag 表和多个 model 有多对多的关联,然后我加了一个中间表

create_table :tag_subject_relations do |t|
  t.integer :tag_id
  t.integer :subject_id
  t.string :subject_type

  t.timestamps null: false
end

通过不同的 subject_type 来确定不同的 model, 用起来是没什么问题,不过在 tag 的 model 那边我想写 has_many 来关联 model 的时候怎么写都不对,最后只能写了个方法来找

model.joins(:tag_subject_relations).where('tag_subject_relations.tag_id = ?', self.id)

平时调用是没什么问题,但是最近在研究 elasticsearch 关联搜索的时候有写 has_many 的几个表都正常,这边就搜索不出结果,所以想问一下像这种情况 has_many 要怎么写?

在 github 上找到了相似的需求代码已解决 https://github.com/sarmad90/sabihrehmani

You need to Sign in before reply, if you don't have an account, please Sign up first.