Rails将生成的js params从表单传递给控制器

时间:2014-06-20 04:56:19

标签: javascript jquery ruby-on-rails ruby ajax

我有一个带有2个日期字段和1个整数的form_for。

  • :start,id:“start”
  • :end,id:“end”
  • :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);
  });
});

变量“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 %>

控制器操作new并创建:

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

允许私人参与:

def vacation_params
  params.require(:vacation).permit(:start, :number_of_days, :end)
end

1 个答案:

答案 0 :(得分:1)

只是看了看你的表格并注意到了这一点:

<div class="large-10 columns left"><%= f.text_field :number_of_days, disabled: true, id: 'number_of_days' %></div>

此字段有已禁用:true ,因此当您提交表单时,其值不会被提交。你需要更新你的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).attr("disable","false");
  });
});

更好的解决方案是让您的字段只读 而不是禁用。你可以通过:

来做到这一点
<div class="large-10 columns left"><%= f.text_field :number_of_days, readonly: true, id: 'number_of_days' %></div>