通过参数重新加载rails 4视图

时间:2015-05-01 00:09:15

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

我有一个带有表单的索引视图,我想通过让用户点击日历上的日期来预先填充来自数据库的表单,这样用户就可以看到该日期存储在其中的日期,并编辑如果他们想要我把它默认设置为今天的日期,它工作正常。如果我将其硬编码到其他日期,它也有效。但是,当我通过单击日期来执行此操作时,表单永远不会重新呈现,它始终显示今天的数据。目前我正在使用ajax调用,我认为这是不正确的。我正在使用gem bootstrap-datepicker-rails作为日历。最好的方法是什么?

这是我的控制器:

def index
    @item = Item.new
    @items = Item.all
    @date = params[:u_date] || Time.now.strftime("%Y-%m-%d")
    @form_items = {}

    @items.each do |item|
      todays_trace = Trace.find_by(item_id: item.id, u_date: @date)
      if todays_trace
        @form_items[item] = todays_trace
      else
        @form_items[item] = Trace.new({input: "", notes: ""})
      end
    end
end

以下是我的观点:

    <div class="row">
      <%= form_tag "/traces_form" do %>
        <div id="datepicker">
          <input name="u_date" type="text" data-provide='datepicker' data-date-format="yyyy-mm-dd" value=<%= @date%>>
        </div>
        <% @form_items.each do |item| %>
          <%= render partial: 'trace_form', :locals => {:item => item[0], :trace => item[1]} %> 
        <% end %>
        <%= submit_tag "submit" %>
      <% end %>
    </div>

这是我的javascript:

<script type="text/javascript">
$("#datepicker").on("changeDate", function(event) {
  var u_date = $("input[name=u_date]").val();

  $.ajax({
    type: "GET",
    url: "/items",
    data: { u_date },
    success: function(){
      console.log("something happened")
    }
  });
});
</script>

点击日期时,这是rails日志:

Started GET "/items?u_date=2015-04-29" for 127.0.0.1 at 2015-04-30 17:04:31 -0700
Processing by ItemsController#index as */*
  Parameters: {"u_date"=>"2015-04-29"}
  Item Load (0.2ms)  SELECT "items".* FROM "items"
  Trace Load (0.1ms)  SELECT  "traces".* FROM "traces" WHERE "traces"."item_id" = ? AND "traces"."u_date" = ? LIMIT 1  [["item_id", 16], ["u_date", "2015-04-29"]]
  Trace Load (0.1ms)  SELECT  "traces".* FROM "traces" WHERE "traces"."item_id" = ? AND "traces"."u_date" = ? LIMIT 1  [["item_id", 17], ["u_date", "2015-04-29"]]
  Trace Load (0.1ms)  SELECT  "traces".* FROM "traces" WHERE "traces"."item_id" = ? AND "traces"."u_date" = ? LIMIT 1  [["item_id", 21], ["u_date", "2015-04-29"]]
  Rendered items/_new_item.html.erb (2.2ms)
  Rendered items/_trace_form.html.erb (0.5ms)
  Rendered items/_trace_form.html.erb (0.2ms)
  Rendered items/_trace_form.html.erb (0.2ms)
  Rendered items/_items.html.erb (9.7ms)
  Rendered items/index.html.erb within layouts/application (20.1ms)
Completed 200 OK in 707ms (Views: 703.6ms | ActiveRecord: 0.4ms)

非常感谢任何帮助。

0 个答案:

没有答案