如何使用“link_to”而不是“checkbox”进行POST?
这个想法是,当用户有missed_day
(又名罢工)时,他会点击此按钮。 他目前可以点击一个复选框来标记missed_day
。
习惯/节目
<label id="" class="habit-id">Strikes: <label id="" class="habit-id-two">Strikes: = (index + 1) %> <p data-submit-url="" data-delete-url=""> <label id="" class="level-id">Level : <label id="" class="level-id-two">Level : 0, {class: "habit-check"} %> 1, {class: "habit-check"} %> 2, {class: "habit-check"} %>
habit.js
$(document).ready(function() { $(".habit-check").change(function() { var submitUrl = $(this).parents("p").data("submit-url"); var deleteUrl = $(this).parents("p").data("delete-url"); if($(this).is(":checked")) { $.ajax( { url: submitUrl, method: "POST" }) .done(function () { location.reload(); }); } else { $.ajax( { url: deleteUrl, method: "DELETE" }) .done(function () { location.reload(); }); } }); });
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 + 2 end level.save! head :ok # this returns an empty response with a 200 success status code end def destroy 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 level.save! head :ok # this returns an empty response with a 200 success status code end private def correct_user @habit = current_user.habits.find(params[:habit_id]) redirect_to habits_path, notice: "Not authorized to edit this habit" if @habit.nil? end end
第一张图片来自主页。 这是两个按钮的代码:
<%= link_to ''.html_safe, mark_completed_path(habit), remote: true, method: 'put', class: 'update_habit', id: 'home_check' %> <%= link_to ''.html_safe, habit_level_days_missed_index_path({ habit_id: @habit.id, level_id: level.id }), remote: true, method: 'put', class: 'habit-check' %>
我们如何让第二个按钮起作用? 这个尝试给了我undefined method 'id' for nil:NilClass
这是它的要点 。
您需要更改此链接
<%= link_to ''.html_safe, habit_level_days_missed_index_path({ habit_id: @habit.id, level_id: level.id }), remote: true, method: 'put', class: 'habit-check' %>
至
<%= link_to ''.html_safe, habit_level_days_missed_index_path({ habit_id: habit, level_id: habit.current_level }), remote: true, method: 'put', class: 'habit-check' %>
- 未捕获的TypeError:undefined不是函数rails3 / backbone / js
- Rails AJAX – 获取下拉选项以填充表格
- “警告:无法validationCSRF令牌真实性”错误 – 使用Devise的CORS和:token_authenticatable
- 如何将remote_form_for的:update =>’div_id’选项从Rails 2升级到Rails 3?
- rails 4 bootstrap 3 ajax modal
- 如何访问只能部分访问的rails变量?
- Rails:在textfield中执行onchange远程函数时如何从另一个字段获取值
- Rails:用户使用以下命令销毁不相关的对象后退出:remote => true
- 如何通过单击视图中的按钮来调用rails中的PLSQL函数?