开发者

Rails has_many through fails on create method

开发者 https://www.devze.com 2023-01-20 04:08 出处:网络
I have 3 Models: User has_many :user_projects has_many :projects,:through => :user_projects Project has_many :user_projects, :dependent => :destroy

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

精彩评论

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