Chad
Chad

Reputation: 61

Rails has_many through fails on create method

I have 3 Models:

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

I then have a form that allows the creation of a new Project and can assign Users to it.

The form is:

<% 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 %>

However, for some reason a record must exist in UserProject table for it to work.

Any idea on how to create the association if it doesn't exist?

Upvotes: 1

Views: 760

Answers (1)

Shreyas
Shreyas

Reputation: 8757

Your associations are incorrect.

User

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

Project

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

UserProject

belongs_to :project 
belongs_to :user

Update your associations as above and post your results.

Upvotes: 1

Related Questions