选中框时,页面如何自动redirect_to @habit
?此行为类似于点击提交按钮。
习惯/显示
<% if @habit.current_level_strike %>
<div class="btn" id="red"> <label id="<%= @habit.id %>" class="habit-id">Strikes:</label>
<% else %>
<div class="btn" id="gold"> <label id="<%= @habit.id %>" class="habit-id-two">Strikes:</label>
<% end %>
<% @habit.levels.each_with_index do |level, index| %>
<% if @habit.current_level >= (index + 1) %>
<p>
<% if @habit.current_level_strike %>
<label id="<%= level.id %>" class="level-id">Level <%= index + 1 %>:</label>
<% else %>
<label id="<%= level.id %>" class="level-id-two">Level <%= index + 1 %>:</label>
<% end %>
<%= check_box_tag nil, true, level.missed_days > 0, {class: "habit-check"} %>
<%= check_box_tag nil, true, level.missed_days > 1, {class: "habit-check"} %>
<%= check_box_tag nil, true, level.missed_days > 2, {class: "habit-check"} %>
</p>
<% end %>
<% end %>
</div>
habit.js
$(document).on("page:change", function()
{
$(".habit-check").change(function()
{
habit = $(this).parent().siblings(".habit-id").first().attr("id");
level = $(this).siblings(".level-id").first().attr("id");
if($(this).is(":checked"))
{
$.ajax(
{
url: "/habits/" + habit + "/levels/" + level + "/days_missed",
method: "POST"
});
}
else
{
$.ajax(
{
url: "/habits/" + habit + "/levels/" + level + "/days_missed/1",
method: "DELETE"
});
}
});
});
days_missed_controller
class DaysMissedController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: [:create, :destroy]
def create
habit = Habit.find(params[:habit_id])
habit.missed_days = habit.missed_days + 1
@habit.save!
level = habit.levels.find(params[:level_id])
level.missed_days = level.missed_days + 1
if level.missed_days == 3
level.missed_days = 0
level.days_lost += habit.calculate_days_lost + 1
end
level.save!
redirect_to @habit, notice: 'Added Strike Against You!' # This message pops up once the user manually goes to a new page, but I'd want the page to automatically redirect_to @habit so that the show page can refresh with the new number of strikes
head :ok
end
The larger issue is this,但我认为实施此功能可能会帮助我进一步澄清更大的问题。
答案 0 :(得分:1)
您只需更改页面的位置,而无需转到服务器。
在JavaScript中:
var habitURL = '<%= raw(habit_url(@habit)) %>';
$('input[type=checkbox]').on('change', function() {
if($(this).prop('checked')) { // Only when it is changed to checked
window.location = habitURL;
}
});
答案 1 :(得分:1)
我想,你想&#34;刷新&#34;用户当前所在的页面。您可以在 habit.js 中执行类似的操作(在完成任何AJAX调用时执行done
):
$(document).on("page:change", function()
{
$(".habit-check").change(function()
{
// ...
if($(this).is(":checked"))
{
$.ajax(
{
url: "/habits/" + habit + "/levels/" + level + "/days_missed",
method: "POST"
})
.done(function () {
location.reload();
});
}
else
{
$.ajax(
{
url: "/habits/" + habit + "/levels/" + level + "/days_missed/1",
method: "DELETE"
})
.done(function () {
location.reload();
});
}
});
});
祝你好运!