我有一个从中创建项目的表单。该表单收集两个表的数据;“项目”和“项目用户”。最后一个是关系表,用于存储哪些用户是项目的成员(在表单中选择)。
创建一个新项目可以正常工作,但是在“projects_users”中创建新帖子时会失败:
uninitialized constant ProjectsController::Projects_users
首先,我是否以正确的方式思考(见下面的代码)?
我所做的是从 params[:project] 中提取成员数组,该数组是从表单中检索的。然后我在数据库中创建项目,完成后我遍历成员数组(包含user_id)并在数据库中为“projects_users”创建帖子。
我究竟做错了什么?有没有更好的方法来实现我想要的?
项目负责人:
class ProjectsController < ApplicationController
def new
@project = Project.new
@users = (current_user.blank? ? User.all : User.find(:all, :conditions => ["id != ?", current_user.id]))
end
def create
@members = params[:project].delete(:members)
@project = Project.new(params[:project].merge(:user_id => current_user.id))
if @project.save
@members.each do |member|
@project_members = Projects_users.new
@project_members.project_id = @project.project_id
@project_members.user_id = member.user_id
end
redirect_to @project
else
@users = (current_user.blank? ? User.all : User.find(:all, :conditions => ["id != ?", current_user.id]))
render :new
end
end
end
新的.html.erb:
<%= form_for @project do |f| %>
<div class="alert alert-block">
<%= f.error_messages %>
</div>
<div class="text_field">
<%= f.label :title%>
<%= f.text_field :title%>
</div>
<div class="text_field">
<%= f.label :description%>
<%= f.text_field :description%>
</div>
<div class="dropdown">
<%= f.label :start_date%>
<%= f.date_select :start_date %>
</div>
<div class="dropdown">
<%= f.label :end_date%>
<%= f.date_select :end_date %>
</div><br/>
<span class="help-block">Välj användare som ska ingå ingå i projektet.</span>
<div class="checkbox">
<% @users.each do |user| %>
<%= check_box_tag "project[members][]", user.id, '1', :id => "user_#{user.id}" %>
<%= label_tag "user_#{user.id}", user.first_name + ' ' + user.last_name, :class => "checkbox" %>
<% end %>
</div>
</div>
<div class="submit">
<%= f.submit "Spara" %>
</div>
<% end %>
项目型号:
class Project < ActiveRecord::Base
has_and_belongs_to_many :users, :class_name => 'User'
belongs_to :user
has_many :tickets, :dependent => :destroy
// validation...
# Setup accessible (or protected) attributes for your model
attr_accessible :user_id, :title, :description, :start_date, :end_date
end
用户型号:
class User < ActiveRecord::Base
attr_accessible :first_name, :last_name, :email, :password
has_and_belongs_to_many :projects
has_many :tickets
... other code
end
projects_users 表:
project_id
user_id
项目表:
user_id (the user that creates the project = admin)
title
description
start_date
end_date