我有一个应用程序,允许用户在名为 Projects 的表中输入和编辑项目。其中一个领域允许他们检查该项目的技术。它们存储在名为 Technols 的单独表中,表之间的关系称为 Projecttechnols。
例如,我有一个 Project X,它有很多技术,tech1、tech2 和 tech3。如果我进入编辑项目,我可以将技术删除或添加到项目中,并随意更新项目。但是,当我尝试将所有项目从项目中删除时,我的问题就开始了。如果我尝试这个,什么都不会改变,技术保持不变。
我创建一个没有技术的新项目没有问题,我可以返回该项目并通过插入技术进行编辑,但如果我返回并添加技术再次编辑它,并尝试将它们全部删除。没发生什么事。
这是我在项目控制器中的新、编辑、创建和更新操作:
def new
@project = Project.new
@technol = Technol.new(params[:tech])
@all_technols = Technol.all
@project_technol = @project.projecttechnols.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @project }
end
end
# GET /projects/1/edit
def edit
@project = Project.find(params[:id])
@project_technol = @project.projecttechnols.build
puts @project.inspect
puts @project.technols.inspect
end
# POST /projects
# POST /projects.json
def create
@project = Project.new(params[:project])
@project.client = params[:new_client] unless params[:new_client].blank?
@project.role = params[:new_role] unless params[:new_role].blank?
@project.industry = params[:new_industry] unless params[:new_industry].blank?
@project.business_div = params[:new_business_div] unless params[:new_business_div].blank?
if !params[:technols].nil?
params[:technols][:id].each do |tech|
if !tech.empty?
@project_technol = @project.projecttechnols.build(:technol_id => tech)
end
end
end
respond_to do |format|
if @project.save
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render json: @project, status: :created, location: @project }
else
format.html { render action: "new" }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
# PUT /projects/1
# PUT /projects/1.json
# PUT /projects/1
# PUT /projects/1.json
def update
@project = Project.find(params[:id])
puts @project.inspect
puts @project.technols.inspect
params['project'][:client] = params[:new_client] unless params[:new_client].blank?
params['project'][:role] = params[:new_role] unless params[:new_role].blank?
params['project'][:industry] = params[:new_industry] unless params[:new_industry].blank?
params['project'][:business_div] = params[:new_business_div] unless params[:new_business_div].blank?
respond_to do |format|
if @project.update_attributes(params[:project])
format.html { redirect_to @project, notice: 'Project was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
这是我对技术位的编辑视图:
<div class="tech" STYLE="text-align: left;">
<b>Technologies:</b>
<style>
.split { text-align:left; }
</style>
<p>
<ul>
<% for technol in Technol.all %>
<li class="split">
<%= check_box_tag "project[technol_ids][]", technol.id, @project.technols.include?(technol) %>
<%= technol.tech %>
</li>
<% end %>
</ul>
</p>
我是 Rails 的新手,所以它可能非常简单。所有帮助将不胜感激。提前致谢。