开发者

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 ass开发者_开发知识库ign 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜