[note] user attention function Rails (a)

Recommended for you: Get network issues from WhatsUp Gold. Not end users.
Here is the whole book is the most difficult part, is split into three parts.


The relationship model:
The difficulty is how to realize the data model of the mutual concern between users, when a user A B or cancel the attention B what happened? There is the creation and destruction of relation.
So the relationship model here, using relationship to achieve, in two, followed_id and follower_id were expressed concern and attention of ID ID.
User and relationship is a one to many relationship, but here's one to many two, one is corresponding to a plurality of followed_id, another is corresponding to a plurality of follower_id, so user has two foreign keys, respectively is followed_id, follower_id.
Similarly, relationship also in two ways from which belongs to user, one is following (that is, in front of the followed), one is folower, which is two user, but took the alias. Both the user ID as the key.
The relationship itself to indexing.


Put up the corresponding code is as follows:
The following User model:

has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
				class_name: "Relationship",
				dependent: :destroy
has_many :followers, through: :reverse_relationships,source: :follower



The relationship model code.:

class Relationship <ActiveRecord::Base
	belongs_to :follower, class_name: "User"
	belongs_to :followed, class_name: "User"
	validates :follower_id, presence: true
	validates :followed_id, presence: true
end





It should be noted that reverse_relationships the table, he actually does not exist, because relationships is a symmetric form, I put the follower_id as a primary key, to query a user pay attention to those people, in turn, I put the followed_id as a primary key, you can query the user how many fans.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Arlen at December 20, 2013 - 10:36 AM