【发布时间】:2018-08-16 12:19:02
【问题描述】:
这些是我的模型:
class User < ActiveRecord::Base
has_many :memberships
has_many :groups, through: :memberships
end
class Group < ActiveRecord::Base
has_many : memberships
has_many :users, through: :memberships
belongs_to :group_type
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
class GroupType < ActiveRecord::Base
has_many :groups
end
我想将组分配给用户。有几种类型的组,用户只能从每种类型中选择一个组。在视图中,每个组类型都应该有一个选择标记(用户不必是每个组类型的成员)。
我可以在成员模型中添加一个 type_id 列,并为每个新用户的每个组创建一个实例,然后更新行,例如(对于类型 1):
<%= form_for (@user) do |f|
<% @membership = Membership.where (user_id: :@user.id, group_type: :1) %>
<%= f.collection_select (:membership, :group_id, Group.all.where(type: 1), :id, :name) %>
<% end %>
(不确定它会起作用)
无论如何,我确信有更好的方法.. 如何将模型与每个类型限制的一组连接起来? (当然还有一种编辑现有成员资格的方法)。
我愿意提供任何帮助...
谢谢!
【问题讨论】:
标签: ruby-on-rails has-many-through collection-select