Reputation: 457
I want to make a table called subject_types
and populate it with different subjects such as english, spanish, history. And assign the subjects
table to each user
. I want the user to be able to select multiple subjects
with a checkbox and it will save those specific ones and keep checked. each user can save their own preferences/services
. Im trying to figure out the best way to approach this.
-Should I make the subject_types
model and populate with these subjects or is there a better approach?
possible solution
subjects
table. How can i do that??Thank you
Updated:
<%= form_for(@user) do |f| %>
<%= f.collection_check_boxes(:writing_type_ids, WritingType.all, :id, :name) %>
<%= f.submit 'submit' %>
<% end %>
class WritingType < ActiveRecord::Base
has_many :user_writing_types
has_many :users, through: :user_writing_types
end
class UserWritingType < ApplicationRecord
belongs_to :user
belongs_to :writing_type
end
class User < ActiveRecord::Base
has_many :user_writing_types
has_many :writing_types, through: :user_writing_types
end
My migration for the join
create_table :user_writing_types do |t|
t.belongs_to :user, index: true
t.belongs_to :writing_type, index: true
t.boolean :active, default: false
t.timestamps
end
latest update
Im getting my last of errors! when i click submit on that page i get No route matches [PATCH] "/users/51"
.
<%= f.collection_check_boxes(:writing_type_ids, WritingType.all, :id, :name) %>
to my edit form in devise
edit.html.erb
. The writing_type names populate on the checkboxes, but nothing gets submitted to the database on the user_writing_type
table.Upvotes: 0
Views: 302
Reputation: 102250
Start by creating a many to many relation with a join model by using has_many :through associations:
class User < ApplicationRecord
has_many :user_subjects
has_many :subjects, through: :user_subjects
end
class Subject < ApplicationRecord
has_many :user_subjects
has_many :users, through: :user_subjects
end
# this is the join model
class UserSubject < ApplicationRecord
belongs_to :user
belongs_to :subject
end
You can then create a check box to add subjects to a user with collection_checkboxes
:
<%= form_for(@user) do |f| %>
<%= f.collection_checkboxes(:subject_ids, Subject.all, :id, :name) %>
# ...
<% end %>
could I have an array in a column in my user table? the array would be the ids of the subjects table. How can i do that??
You don't.
Even though Postgres for example allows you to create array type columns it is not a good solution as thats not how associations work in ActiveRecord.
Its also a crappy relational database design as its messy to write queries with a join though an array column and it does not let you enforce referential integrity with foreign keys or have good indices for performance.
Upvotes: 1