在 Rails 的 Ruby 中使用 Ajax 更改局部 Ruby 变量

Change local Ruby variable with Ajax in Ruby on Rails

我正在创建一个显示每周计划的日程安排页面,并希望在页面底部制作箭头,以一周向前和向后切换。为此,我在控制器中创建了一个变量,@wbeg,默认为一周的开始和两个动作,week_after 和 week_before,以及各自的 js.erb 文件。我不知道如何使用 ajax 更改 @wbeg 变量,需要这样做才能将所有内容保持在同一页面上。

这里是控制器:

class HomeController < ApplicationController

    def home
    end

    def scheduling
        @work_days = WorkDay.all
        @jobs = Job.all
        @wbeg = Date.today - Date.today.wday + 1 #beginning of this week
    end

    def week_before
        respond_to do |format|
            format.html { redirect_to scheduling_path notice: "You should not see this message, contact admin if you do."}
            format.js
        end
    end

    def week_after
        respond_to do |format|
            format.html { redirect_to scheduling_path notice: "You should not see this message, contact admin if you do."}
            format.js
        end
    end

end

日程安排页面:

<p id="notice"><%= notice %></p>

<h1>Work Day Scheduling</h1>

<table>
    <thead>
        <tr>
            <th>Job #</th>
            <th>Job</th>
            <th>Monday</th>
            <th>Tuesday</th>
            <th>Wednesday</th>
            <th>Thursday</th>
            <th>Friday</th>
            <th>Saturday</th>
        </tr>
    </thead>
    <tbody id = "main_table">
        <%= render "home/main_table" %>
    </tbody>
</table>
<%= link_to '<--', week_before_path, remote: true %>
<%= link_to '-->', week_after_path, remote: true %>

和两个 js.erb 页面:

$('#main_table').html("<%= j render 'main_table', locals: { wbeg: @wbeg - 7 } %>");

其他:

$('#main_table').html("<%= j render 'main_table', locals: { wbeg: @wbeg + 7 } %>");

我也已经尝试过更改 week_before 中的变量以及在控制器中执行操作后,但它给出了相同的错误 'nil cannot have operation "-"' 或其他错误,这只是意味着它无法识别变量。

按照您现在的编码方式,生成 javascript 文件时 @wbeg 变量的值将被硬编码到 javascript 文件中。该值永远不会改变。无论生成 javascript 时是什么。

您需要的是一个 javascript 变量,您可以在调用 AJAX 的 javascript 代码中更新它。