我有一個form_for,包含2個日期字段和1個整數。Rails將生成的js參數從窗體傳遞到控制器
- :開始,ID: 「開始」
- :年底ID: 「結束」
- :NUMBER_OF_DAYS,ID: 「NUMBER_OF_DAYS」
我的JS:
$(document).ready(function(){
$("#start, #end").on('change', function() {
var start = $('#start').datepicker('getDate');
var end = $('#end').datepicker('getDate');
var duration = (end.getDate() - start.getDate())/1000/60/60/24;
$("#number_of_days").val(duration);
});
});
變量「持續時間」的值在表格中的number_of_days字段中顯示爲罰款,但如何在提交表單時將生成的:number_of_days傳遞給控制器?
謝謝
編輯: 的form_for:
<%= form_for(@vacation) do |f| %>
<div class="row">
<div class="large-2 columns"><%= f.label :start, "Starts On" %></div>
<div class="large-10 columns left"><%= f.text_field :start, data:{ type: 'date'}, id: 'start' %></div>
</div>
<div class="row">
<div class="large-2 columns"><%= f.label :end, "Ends On" %></div>
<div class="large-10 columns left"><%= f.text_field :end, id: 'end' %></div>
</div>
<div class="row">
<div class="large-2 columns"><%= f.label :number_of_days, "Duration In Days" %></div>
<div class="large-10 columns left"><%= f.text_field :number_of_days, disabled: true, id: 'number_of_days' %></div>
</div>
<div class="row">
<div class="large-10 large-offset-2 columns">
<%= f.submit nil, class: 'button small radius success' %>
</div>
</div>
<% end %>
控制器動作新創建:
def new
@vacation = Vacation.new
end
def create
@vacation = Vacation.new(vacation_params)
@vacation.user = current_user
@vacation.number_of_days = params[:number_of_days]
respond_to do |format|
if @vacation.save
format.html { redirect_to @vacation, notice: 'Vacation was successfully created.' }
else
format.html { render action: 'new'}
end
end
end
許可證PARAMS私下:
def vacation_params
params.require(:vacation).permit(:start, :number_of_days, :end)
end
你可以嘗試找出與紅寶石的區別...你已經有嗎? – jandresrodriguez
它實際上是我的項目中要求在提交表單之前立即在指定的text_field中顯示天數.. – Shalaby
number_of_days值是否在控制器的params散列中不存在? –