我有 3 个模型:
User
has_many :user_projects
has_many :projects, :through => :user_projects
Project
has_many :user_projects, :dependent => :destroy
has_many :users, :through => :user_projects, :uniq => true
UserProject
belongs_to :project
belongs_to :user
然后我有一个表单,允许创建一个新项目并可以将用户分配给它。
表格是:
<% form_for(@project, :html => { :id => 'project_create'}) do |f| %>
<%= f.label :name, 'Project Name' %>
<% @users.each do |user| %>
<%= user.username %>: <%= check_box_tag("project[user_project_ids][]",user.id) %>
<% end %>
<% end %>
但是,由于某种原因,表中必须存在一条记录才能UserProject
正常工作。
如果它不存在,关于如何创建关联的任何想法?