1

我有 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正常工作。

如果它不存在,关于如何创建关联的任何想法?

4

1 回答 1

1

您的关联不正确。

用户

has_many :user_projects
has_many :projects, :through => :user_projects

项目

has_many :user_projects, :dependent => :destroy 
has_many :users, :through => user_projects

用户项目

belongs_to :project 
belongs_to :user

如上所述更新您的关联并发布您的结果。

于 2010-10-12T16:56:46.380 回答