2017-10-19 55 views
0

我有一个表格,看起来像这样:渲染过程中的表单提交AJAX Rails中js.erb文件

<div class= "parent-container"> 
    <%= form_with scope: @company, url: companies_path, html: { class: "form-inline", remote: true, "data-type" => :js, id: "new-company-create" }, local: true do |f| %> 
    <div class= "form-group"> 
     <%= f.label :nil, 'Company Name:', :class => 'sr-only'%> 
     <%= f.text_field :nil, :class => 'form-control-plaintext' %> 
    </div> 
    <div class="form-group mx-sm-3"> 
     <%= f.label :name, 'Enter a Company Name : ' %> 
     <%= f.text_field :name, :class => 'form-control large-input-grp', :placeholder => "Enter any Company Name" %>  
    </div> 
    <%= button_to "Create a Company", companies_path, class: "btn btn-default", id: "create_company_main", :type => "submit", :method => "post"%> 
    <% end %> 
</div> 

这我想通过AJAX Rails的提交和认识什么是痛苦一个简单的过程可以。

在我的控制器,形式职位,以这种方法:

def create 
    @newCompany = Company.new(company_params) 
    respond_to do |format| 
    if @newCompany.save 
     format.js 
     format.html { render :nothing => true, :notice => 'Company created successfully!' } 
     format.json { render json: @newCompany, status: :created, location: @newCompany } 
    else 
     format.html { render action: "new" } 
     format.json { render json: @newCompany, status: :unprocessable_entity } 
    end 
    end  
end 

和我在respond_to do |format|块尝试多种组合,但似乎没有奏效。

我没有做,似乎是返回我的_create.js.erb文件,而不是寻找一个HTML。

在我的终端,我可以看到POST请求过程中出现如下显示:

Processing by CompaniesController#create as HTML 

,我可以看到关于这都是过时的,我想了解的教程一步,但我轨一步我陷入了这么基本的事情中。

不知道为什么我必须做format.htmlformat.json,即使我想从控制器获取JS文件,以及如何从控制器获取js.erb文件。

+0

为什么你需要提及' “数据类型”=>:TRUE':当你alredy提到的'远程js'? – Gabbar

+0

我正在尝试不同的选项。只保持远程:没有工作。 – user122121

+0

'remote:true'不应该在'html'中,而应该直接以* form_with * param的形式传递,比如'url:companies_path'。 –

回答

2

它发送的HTML请求,因为您提到了提交按钮上的链接,其行为如同<a href="/compaines">Create a Company</a>,并且它在不提交表单的情况下触发了您的操作。

试试这个: -

<%= form_for(@company, url: companies_path_path, :html => { class: "form-inline", id: "new-company-create" },remote: true, method: 'POST') do |f| %> 
    <div class= "form-group"> 
    <%= f.label :nil, 'Company Name:', :class => 'sr-only'%> 
    <%= f.text_field :nil, :class => 'form-control-plaintext' %> 
    </div> 
    <div class="form-group mx-sm-3"> 
    <%= f.label :name, 'Enter a Company Name : ' %> 
    <%= f.text_field :name, :class => 'form-control large-input-grp', :placeholder => "Enter any Company Name" %>  
    </div> 

    <%= button_tag(type: 'submit', class: "btn btn-default", id: "create_company_main") do %> 
    Create a Company 
    <% end %> 
<%end%> 
+0

我做了一些更改,请再次看看, 它的发送html请求,因为您提到了提交按钮上的链接。 请尝试这个新的代码,希望它会发送ajax请求到您的控制器 – Gabbar

+0

谢谢,它的工作!我错在哪里? – user122121

+0

因此,在提交按钮中添加链接就是答案,您应该在答案上更新该答案。非常感谢你btw! – user122121