rails polymorphic model implementation

拜拜、爱过 提交于 2020-01-06 11:25:54

问题


In my project, I have a relationship model that allow users to follow each other.

class Relationship < ActiveRecord::Base
  attr_accessible :followed_id

  belongs_to :follower, :class_name => "User"
  belongs_to :followed, :class_name => "User"

end

Now, I want to also allow users to follow courses and groups. Do I start a new followedCourse and followedGroup model or do I make the relationship model polymorphic? How do I do that? Thanks.


回答1:


I wouldn't use polymorphic for potentially-large tables. I think the best way to go is to use has_and_belongs_to_many relationships for this kind of relation.

Remember to create indexes on user_id, group_id to speed up things a bit. You can do that by using add_index(:table_name,[:user_id,:group_id]).

I would also make the relation UNIQUE, which you can do appending :unique => true at the end of the add_index command.



来源:https://stackoverflow.com/questions/5657208/rails-polymorphic-model-implementation

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