2017-10-19 83 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