Rails - users have many users through comments

I am trying to create a comment system that allows users to post to other user pages through comments.

The user will have a comment on his page, which is sent by another user called a commenter.

1) Is the following code a legit / functional / decent design?

2) Is it good to have a renamed “commentator” user combined with an un renamed “user” or should all user association names always be renamed semantically?

3) Are there better ways to implement this design intent (for example, not having has_many done through :)?

class User < ActiveRecord::Base
  has_many :comments
  has_many :users,      through: :comments
  has_many :commenters, through: :comments, class_name: 'User'  
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :commenter, class_name: 'User'
end

Note:

, , (, , ). , has_many .

0
3

, , - has_many has_many . , , :

class User < ActiveRecord::Base
  has_many :owned_comments, class_name: 'Comments', foreign_key: 'owner_id'
  has_many :posted_comments, class_name: 'Comments', foreign_key: 'commenter_id'
end

class Comment < ActiveRecord::Base
  belongs_to :owner, class_name: 'User'
  belongs_to :commenter, class_name: 'User'
end
+4
+1

I implemented similar functionality in mongoids and rails. The models were User, Friendship and Request. Its as a user sends a request to a friend to another user.

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  devise :invitable, :database_authenticatable, :registerable, :recoverable,
    :rememberable, :trackable, :validatable, :confirmable
  ...
  has_many :requests_from, class_name: "Request", inverse_of: :requested_by
  has_many :requests_to, class_name: "Request", inverse_of: :requested_to
  has_many :friendships, inverse_of: :owner

  def friends
    #retrive all the friendships and collect users have sent me a request or being sent a request.
    fs = Friendship.any_of({:friend_id.in => [self.id]}, {:owner_id.in => [self.id]}).where(state: 'accepted')
    User.in(id: fs.collect{|i| [i.friend_id, i.owner_id]}.flatten - [self.id])
  end
end#User

class Friendship
  include Mongoid::Document
  include Mongoid::Timestamps

  field :state, type: String, default: 'pending'
  field :pending, type: Boolean, default: true

  belongs_to :owner, class_name: 'User'
  belongs_to :friend, class_name: "User"

  validates :state, inclusion: { in: ["pending", "accepted", "rejected"]}
  ...
end#Friendship

class Request
  include Mongoid::Document
  include Mongoid::Timestamps

  field :state, type: String, default: 'pending'

  belongs_to :requested_by, class_name: 'User', inverse_of: :requests_from
  belongs_to :requested_to, class_name: 'User', inverse_of: :requests_to

  validates :state, inclusion: { in: ["pending", "accepted", "rejected"]}
  ...
end#Request

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1534589/


All Articles