views:

38

answers:

1

Hi,

Say 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?

Any help would be much appreciated.

Cheers

A: 

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.

Shreyas Satish
Hi ShreyasNot sure why it wasn't in there, blind copy/paste - down to tiredness I guess!Updated model associationsSame result:Couldn't find all UserProjects with IDs (1,2)Its running:SELECT * FROM `user_projects` WHERE (`user_projects`.`id` IN (1,2)) Seems to be using the ID of the user to try and find a user_project row (which doesn't exist)
Chad
Have you tried using formtastic ? Its much easier dealing with forms such as these using it. It automatically detects associations.
Shreyas Satish
I'm on a machine that doesn't have admin priviledges, and so cannot install Bundler which is what Formtastic requires :/
Chad