新手问题 请教一个关于 polymorphic 的问题

dccmmtop · July 25, 2017 · Last by small_fish__ replied at July 26, 2017 · 1241 hits

图中的 as: 该如何理解呢??

分别去掉 :as ,再加上 :as 试试 @product.pictures 就知道了

pictures 里肯定有 2 个字段,xxx_type,xxx_id,这个 as 关键字改变的就是 xxx 这部分,如果你在 employees 没有使用 as,那么当你 Employee.first.pictures,查看生成的 sql,去查找的就是 pictures 表里的 employee_id,但你用了 as 后,比如 as: :item,找的那个外键就成了 item_id。

如 1 楼说,自己试试有 as 和没 as 时 Employee.first.pictures 生成的 sql 就明白了。

哦哦,我试一下

as 这个翻译过来也很好理解嘛,毕竟多态不是一对一,你不可能写成 Picture belongs_to Employee 吧,这样就没法复用

dccmmtop closed this topic. 16 Dec 16:50
You need to Sign in before reply, if you don't have an account, please Sign up first.