我是 Rails 的新手,所以我可能会以某种方式(显然)搞砸了。我有一个通过 ajax 将提交发送回控制器的表单。
这是那个文件/index.html.erb/
<% provide(:title,'PlanYourTask') %>
<div class="mycontainer">
<div class="myprojcont container">
<div class="row yourprojects" id="yourproject_<%=current_user.id%>">
<% if @projects.any? %>
<%@projects.each do |project| %>
<%=render 'projects/projects',:project => project %>
<%end%>
<%end%>
<div class="col-md-3 col-xs-12 newproject">
<a class="btn btn-warning" style="border-bottom-left-radius:0px;border-bottom-right-radius:0px;display:block;">Create New Project
</a>
<div class="dropdownnewproject">
<div class="projectdropdown" style="background:#bbb;border-bottom-left-radius:5px;border-bottom-right-radius:5px;margin:auto;padding:2px;
display:block;">
<p class="example-description">Enter the name of the project</p>
<%=form_for Project.new,:remote => true do |f|%>
<%=f.text_field :name,class:'form-control'%>
<%=f.submit class:'col-md-6 btn btn-success'%>
<%end%>
<a href="#" class="closeproject"><i class="fa fa-times fa-lg" style="margin:10px auto;"></i></a>
</div>
</div>
</div>
<script type="text/javascript">
$('.newproject > a').click(function(e){
$('.dropdownnewproject').slideDown(1000);
e.preventDefault();
});
$('.closeproject').click(function(e){
$('.dropdownnewproject').slideUp(1000);
e.preventDefault();
});
</script>
</div>
</div>
</div>
如果您可以看到其中有一个表单,它会发送一个 ajax 请求以创建新项目。
项目控制器在这里
class ProjectsController < ApplicationController
before_filter :require_user
def new
@projects=current_user.projects
@project=current_user.projects.new
end
def create
@project=current_user.projects.create(params[:project])
respond_to do |format|
if @project.save
format.html{redirect_to :projects}
format.js
flash[:success]="Project created successfully"
else
render new
end
end
end
def show
@project=Project.find(params[:id])
end
def index
@projects=current_user.projects
end
end
最后是我的 create.js.erb 文件
$('#yourprojects_<%=current_user.id%>').append('<%=j render partial:"projects/projects", object: @project %>');
/projects/projects.html.erb/ _ _
<div class="col-md-3 projects" style="margin-bottom:15px;">
<p style="font-family:TimesNewRoman;font-size:25px;margin:25px auto;text-align:center;"><%=link_to project.name,project,style:'text-decoration:none;'%></p>
</div>
/项目.rb文件/
class Project < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
validates :name,presence: :true
validates :description,presence: :true
has_many :tasks,dependent: :destroy
has_many :assigns,dependent: :destroy
has_many :subtasks,through: :tasks
has_many :users,through: :assigns
after_create :add_tasks
private
def add_tasks
self.tasks.build(taskname: "Production")
self.tasks.build(taskname: "Development")
self.tasks.build(taskname: "Test")
end
end
当我在 chrome 中检查我的网络选项卡时单击提交按钮,它会向 /projects 发送一个发布请求,但错误是 406 不可接受。
有人可以帮我解决这个问题。