Users are free to create groups and can also belong to groups created by other users. Members who join the group will also be able to speak freely within the group.
If you put this mechanism on the table, Since users and groups have a many-to-many relationship, we will use an intermediate table. And since there is a many-to-many relationship between users and posts within the group, we also use an intermediate table.
The ER diagram looks like this. (I'm sorry for handwriting ...)
The previous ER diagram has the following associations.
class Group < ApplicationRecord validates :name, presence: true, uniqueness: true has_many :group_users has_many :users, through: :group_users has_many :groupposts accepts_nested_attributes_for :group_users end
class GroupUser < ApplicationRecord belongs_to :group belongs_to :user end
class Grouppost < ApplicationRecord belongs_to :group belongs_to :user end
class GroupsController < ApplicationController def new @group = Group.new @group.users << current_user end def create if Group.create(group_params) redirect_to groups_path, notice: 'I created a group' else render :new end end def index @groups = Group.all.order(updated_at: :desc) end def show @group = Group.find_by(id: params[:id]) if [email protected]?(current_user) @group.users << current_user end @groupposts = Grouppost.where(group_id: @group.id).all end private def group_params params.require(:group).permit(:name, :user_id ) end def grouppost_params params.require(:grouppost).permit(:content) end end
The basic design is the same as around the user.
def show . . if [email protected]?(current_user) @group.users << current_user end end
In this way, people who follow the link of a group can belong to that group.
class GrouppostsController < ApplicationController def new @grouppost = current_user.groupposts.new @group = Group.find_by(id: params[:group_id]) end def create @group = Group.find_by(id: params[:group_id]) @grouppost = current_user.groupposts.new(grouppost_params) @grouppost.group_id = params[:group_id] if @grouppost.save redirect_to group_path(@group.id) end end private def grouppost_params params.require(:grouppost).permit(:content) end end
This also has the same shape as the posting function created earlier.
With the above, the 2ch small group function (bulletin board style) is completed. As a future task, I would like to be able to lock when creating a group and create an invitation-only group.