【问题标题】:Rails 4 x simple_calendar gem: create new record on click in calendar cellRails 4 x simple_calendar gem:在日历单元格中单击时创建新记录
【发布时间】:2016-01-23 00:02:37
【问题描述】:

我有一个带有 Post 模型和 Calendar 模型的 Rails 4 应用程序:post belongs_to calendar 和 calendar has_many posts。

Post 模型有一个自定义的:date 属性。

帖子以两种不同的视图显示:

  • 作为标准Calendars#Show 视图中的列表
  • 作为自定义 Calendars#Calendar_view 视图中的日历

我想要实现的是,让用户只需在Calendars#Calendar_view 视图中单击日历的一个单元格即可创建新帖子,也就是说转到Posts#New 视图,其中新帖子的:date 字段将预先填写单元格中的日期。

我在calendar_view 视图中使用simple_calendar gem 来显示帖子,代码如下:

<%= month_calendar events: @posts do |date,posts| %>
  <%= content_tag :div, class: "new-event", data: {date: date} do %>
    <%= date.strftime('%e') %>
    <% posts.each do |post| %>
      <div class="single_event">
        <%= link_to post.subject, post_path(post) %>
      </div>
    <% end %>
  <% end %>
<% end %>

我在我的posts.coffee 文件中使用此代码来检测on click 事件并从单元格中获取日期:

$(".new-event").on "click", (e) ->
  date = $(this).data("date")
  window.location = "/posts/new?post[date]=#{date}"

然后,在我的Posts#New 操作中,我使用@post = @calendar.posts.new(post_params) 从表单中的单元格中预加载日期。

问题是:当我在calendar_view 视图中单击一个单元格时,什么也没有发生。

我在 Chrome 中检查了控制台,没有出现错误。

知道这里出了什么问题,或者至少我应该从哪里开始调试?

【问题讨论】:

    标签: javascript ruby-on-rails ruby-on-rails-4 coffeescript calendar


    【解决方案1】:

    看看这个例子:https://github.com/excid3/clickable-simple_calendar

    你可以使用这个 JS 来触发重定向。我的位置重定向错了,这就是你想要的:

    jQuery ->
      $(".calendar-day").on "click", ->
        date = $(this).data("date")
        location.href = "/meetings/new?meeting[start_time]=#{date}"
    

    这一切都与日历的 HTML 挂钩:

    <%= month_calendar do |day| %>
      <%= content_tag :div, class: "calendar-day", data: {date: day} do %>
        <%= day %>
        <%# Whatever else you want in here %>
      <% end %>
    <% end %>
    

    还有一点改变了 Meetings 新操作,它使用 strong_params 使用参数预填充它(如果它丢失也不会抛出错误)。

    这应该可以解决问题!

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多