What you want is a join table between your User and Interest models
You want to have something like this
users table
id
1
2
3
interests table
id name
1 "interest 1"
2 "interest 2"
3 "interest 3"
interest_users table (the join table)
id interest_id user_id
1 1 1 # User 1 is interesed in interest 1
1 2 1 # User 1 is interesed in interest 2
1 3 1 # User 1 is interesed in interest 3
1 3 2 # User 2 is interesed in interest 3
User 3 is interesed in nothing!
Let's do it with rails
First create the join_table through a migration, create_join_table rails documentation
# db/create_join_table_user_interest.rb
class CreateJoinTableUserInterest < ActiveRecord::Migration[5.1]
def change
create_join_table :user, :interest do |t|
t.index %i[user_ud interest_id]
t.index %i[interest_id user_ud]
end
end
end
Then create the joining model InterestUser, each row of the joining model belongs to both table!
# models/user_interest.rb
class InterestUser < ApplicationRecord
belongs_to :user
belongs_to :interest
end
Update your models to tell it, it has interests (look at the rails through tutorial )
# model/user.rb
class User < ApplicationRecord
has_many :user_interests
has_many :interests, through: :user_interest
end
# model/interest.rb
class Interest < ApplicationRecord
has_many :user_interests
has_many :user, through: :user_interest
end