2017-10-09 70 views
1

在我的Rails應用程序中,創建新記錄後得到最後一筆費用記錄的重複,但我想在重複數爲:description_other,「」時排除一個屬性。在Rails中複製記錄除了一個屬性?

expenses_controller.rb

class ExpensesController < ApplicationController 

# GET /expenses/new 
    def new 
    if Expense.last.present? 
     @expense = Expense.last.dup 
    else 
     @expense = Expense.new 
    end 
    end 

def expense_params 
     params.require(:expense).permit(:date, :description, :description_other, :trips, :fare, :credit) 
    end 
end 

_form.html.erb

<div class="row"> 
    <div class="col-md-3 col-md-offset-4"> 

    <%= form_for(@expense) do |f| %> 

    <div class="form-group"> 
    <%= f.label :date %><br> 
    <span class="datetime"><%= f.date_select :date %></span> 
    </div> 

    <div class="form-group"> 
     <%= f.label :credit %><br> 
     <%= f.text_field :credit, class: "form-control" %> 
    </div> 

    <div class="form-group"> 
    <%= f.label :description %><br> 
    <%= f.select(:description, options_for_select([['PLEASE SELECT...', ''],['METRO', 'METRO'], ['BUS', 'BUS'], ['TAXI', 'TAXI'], ['OTHERS', 'OTHERS'], ['FOOTLOOSE', 'FOOTLOOSE']]), {}, {class: "form-control", id: "expense_description"}) %> 
    <br> 
    <div id="otherDesc"> 
    <%= f.text_field :description_other, class: "form-control" %> 
    </div> 
</div> 

    <div class="form-group"> 
    <%= f.label :trips %><br> 
    <%= f.number_field :trips, class: "form-control" %> 
    </div> 

    <div class="form-group"> 
    <%= f.label :fare %><br> 
    <%= f.text_field :fare, class: "form-control" %> 
    </div> 

    <br> 
    <div style="margin-left: 70px;" class="form-group"> 
    <%= f.submit @expense.new_record? ? "Create Expense" : "Update Expense", class: "btn btn-lg btn-primary" %> 
    </div> 

    <% end %> 

</div> 
</div> 

我都試過,但無法得到期望的結果。

任何建議是最受歡迎的。

預先感謝您。

回答

1

您應該添加

<div id="otherDesc"> 
<%= f.text_field :description_other, class: "form-control", value: " "%> 
</div> 
+0

好極了!它正在按預期工作,而且更少的修改。 –

+0

@MuhammadYaseen它不會工作兄弟。什麼是第一次費用創作。我將填補其他Desc字段零 – krishnar

1

使用自來水,然後通過設置排除屬性零

def new 
    if Expense.last.present? 
    # exclude here 
    @expense = Expense.last.dup.tap do | exp | 
        exp.description_other = nil 
       end 
    else 
    @expense = Expense.new 
    end 
end 
+0

感謝您的答覆。我得到的功能工作,但當我創建一個新的開支,它指向更新行動。 –

+0

@MuhammadYaseen因爲費用對象已經存在。 – krishnar

+0

@MuhammadYaseen你期待什麼?只打創建動作? – krishnar

相關問題