Building a multi table relationship in Rails ActiveRecord

♀尐吖头ヾ 提交于 2019-12-13 04:34:04

问题


I have the following models in Rails:

Player
Match
Series

And a Post model:

Post

I want to link each post to one of the above model. Need to create a new table that will have

Object_type - player or match or series
Object_id - Id of above object
Post_id

Is there a built in way to create such relationship in rails? and easily access a player's post like player.posts? (that will filter for object_type = 'player' in this relationship table)


回答1:


Use Polymorphic Associations to manage relationships. Refer http://guides.rubyonrails.org/association_basics.html#polymorphic-associations




回答2:


You can use STI (single table inheritance) for that for more detail read follow this link

http://www.therailworld.com/posts/18-Single-Table-Inheritance-with-Rails



来源:https://stackoverflow.com/questions/20880755/building-a-multi-table-relationship-in-rails-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!