I'm trying to design the database model hierarchy and the migrations for my database for a group chat app and I'm new to rails so I'm quite confused about how I should build this... Any guidance would be greatly appreciated!
It breaks down as follows:
Groups <==> Users <==> Posts
Groups ==> Posts
So the groups have a bunch of users and users have a bunch of groups, but also the groups have the posts that the users make. Each post belongs to one group and one user. The post must also maintain a reference to the user that posted it.
Should I just make a joined table of all 3? Is that practical/efficient?
I'm just confused where I should use belongs_to
, has_one
, has_many
, has_and_belongs_to_many
and how I should write the migration files...
thanks for any help ahead of time
you can do it in next way
Groups
has_and_belongs_to_many :users
has_many :posts
Users
has_and_belongs_to_many :groups
has_many :posts
Posts
belongs_to :group
belongs_to :user
posts
table should have group_id
and user_id
columns also create table groups_users
migration:
class CreateGroupsUsers < ActiveRecord::Migration
def change
create_table :groups_users, id: false do |t|
t.references :group, index: true
t.references :user, index: true
end
end
end
This should work!
EDIT
for adding association between User and Group:
group = Group.create(name: 'New Group')
user = User.last
user.groups << group
or
user.build_group(name: 'New Group')
user.save
or you can use nested_attributes
User.create(params[:user])
where params[:user] = {user_name: 'James Bond', group_attributes: {name: 'New Group'}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.