我试图对数据库进行查询,以获取每次用户在jQuery UI日期选择器中更改月份时该月份的可用日期。当他们选择日期时,它将向数据库再次查询该天的可用小时数。


我应该那样做吗?我应该将其更改为每年一次吗?会不会有太多的记录? (我觉得如果我要发送一年中哪些天可用的时间)。
如何正确执行此操作?进行Ajax调用时,出现“找不到模板”。


相关代码:

task_controller.rb

def new
  if signed_in?
    @task = Task.new
    get_dates
  else
    redirect_to root_path
  end
end

def get_dates(day=nil)

    if !day
      day = DateTime.now
    end
    day = day.utc.midnight

    minus_one_month = (day - 1.month).to_time.to_i
    plus_one_month = (day + 1.month).to_time.to_i

    full_days_results = AvailableDates.all.select(['unix_day, count(*) as hour_count']).group('unix_day').having('hour_count > 23').where(unix_day: (minus_one_month..plus_one_month))

    full_days_arr = full_days_results.flatten

    full_unix_array = []

    full_days_arr.each do |full_day|
      tmp_date = Time.at(full_day.unix_day).strftime('%m-%d-%Y')
      full_unix_array.append(tmp_date)
    end

    gon.full_days = full_unix_array

    return
end


task.js.coffee

full_days = gon.full_days if gon
$ ->
  $('.datepicker').datepicker(
    dateFormat: 'mm-dd-yy'
    beforeShowDay: available
    onChangeMonthYear: (year, month, inst) ->
      target = "#{month}-01-#{year}"
      jqxhr = $.get("/getdates",
        day: target
      )
      console.log(jqxhr)
      $(this).val target
      return


task \ new.html.erb

<%= f.label :end_time %>
<%= f.text_field :end_time, :class => 'datepicker' %>


routes.rb

...
match '/getdates',to: 'tasks#get_dates',      via: 'get'


错误

Template is missing

Missing template tasks/get_dates, application/get_dates with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in: * "c:/dev/rails_projects/onager-web-app/app/views"

最佳答案

好吧,您需要做几件事:

1-将get_dates设为私有(并选择更像红宝石的名称)

private

def hours_for(day=nil)
...
end


Rails认为get_dates实际上不是控制器动作。这就是为什么它找不到get_dates动作的相应视图的原因(当它不是动作时,它是一个辅助方法,也许您应该考虑将其放入模型中)

2-hour_for方法应该返回一些内容。现在不是。我不知道这行是做什么的:

gon.full_days = full_unix_array


我的意思是,gon是什么?只需直接返回数组。您不应该在get方法中设置内容。另外,看看this以了解如何在Rails页面中呈现json。

3-在rails项目的controllers文件夹中将task.rb重命名为task_controller.rb。

4-将route.rb文件修复为:

get '/getdates/:day', to: 'tasks#load_dates', as: 'getdates'


另外,hours_for必须在load_dates调用。您在任务中的“新”操作应呈现一个模板,并且每次用户更新日期时,您的coffeescript都应调用load_dates ajax方法。

现在,您需要做的是学习如何更新new.html.erb页面。

关于javascript - Ajax调用rails返回缺少模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24434351/

10-11 22:25
查看更多