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



我正在创建一个显示每周时间表的计划页面,并希望在页面底部制作每周向前和向后切换的箭头。为此,我在控制器 @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 不能有操作"-"或其他东西,这只是意味着它无法识别变量。

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

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

最新更新