我想创建一个名为subject_types
的表格,并用不同的主题填充它,例如英语,西班牙语,历史。并将subjects
表分配给每个user
。我希望用户能够使用复选框选择多个subjects
,它将保存这些特定的并保持选中状态。每个用户都可以保存自己的preferences/services
。我试图找出解决这个问题的最佳方法。
- 我应该制作subject_types
模型并填充这些主题还是有更好的方法?
可能的解决方案
subjects
表的id。我怎么能这样做?谢谢
更新
<%= 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
我的加入迁移
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
最新更新
我得到了我最后的错误!当我点击该页面上的提交时,我得到No route matches [PATCH] "/users/51"
。
<%= f.collection_check_boxes(:writing_type_ids, WritingType.all, :id, :name) %>
添加到devise
edit.html.erb
的编辑表单中。 writ_type名称填充在复选框上,但没有任何内容提交到user_writing_type
表上的数据库。答案 0 :(得分:1)
首先使用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
然后,您可以创建一个复选框,将主题添加到collection_checkboxes
的用户:
<%= form_for(@user) do |f| %>
<%= f.collection_checkboxes(:subject_ids, Subject.all, :id, :name) %>
# ...
<% end %>
我的用户表中的列中是否有数组?数组将是 主题表的ID。我怎么能这样做?
你没有。
即使Postgres允许您创建数组类型列 这不是一个好的解决方案,因为那不是协会在ActiveRecord中的工作方式。
它也是一个糟糕的关系数据库设计,因为它通过数组列使用连接编写查询时很麻烦,并且它不允许您使用外键强制引用完整性或具有良好的性能索引。