Reputation: 8587
Whats the best method on tagging users? If you have a team model, and when you create a team, you want to add the members, how would this architecture work?
I was thinking of just using acts as tanggble and use it on the users, but not sure if this would be the best method? Is there another gem out there that would do something like this?
Upvotes: 2
Views: 251
Reputation: 76784
To add to @tpbowden
's answer, if you just want to "tag" users, you may wish to use has_and_belongs_to_many
:
# app/models/user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :teams
end
# join table "teams_users" - team_id | user_id
# app/models/team.rb
class Team < ActiveRecord::Base
has_and_belongs_to_many :users
end
This will allow you to use the singular_collection_ids
method, with which you'll be able to define which user is in a "team":
#app/controllers/teams_controller.rb
class TeamsController < ApplicationController
def edit
@team = Team.find params[:id]
end
def update
@team = Team.find params[:id]
@team.update team_params
end
private
def team_params
params.require(:team).permit(user_ids: [])
end
end
#app/views/teams/edit.html.erb
<%= form_for @team do |f| %>
<%= f.collection_select :user_ids, User.all, :id, :name %>
<%= f.submit %>
<% end %>
This is as close to "tagging" as you're going to get without any extra dependencies.
Upvotes: 0
Reputation: 2090
It sounds like you're looking for a has many through
relationship. This would require you to have a joining table called team_members
to record which users are members of each team, having user_id
and team_id
columns. So for example your Team model would have a relationship that looks like this:
has_many :users, through: :team_members
This then defines the appropriate method on Team for adding, querying and removing users.
More information is here
Upvotes: 2