1

I'm creating a scheduling page that shows a weekly schedule and want to make arrows at the bottom of the page that switch forward and backward a week. To do this I'm creating a variable in the controller, @wbeg, that defaults to the beginning of the week and two actions, week_after and week_before, with respective js.erb files. I can't figure out how to change the @wbeg variable using ajax and need to do so to keep everything on the same page.

Here is the controller:

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

The scheduling page:

<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 %>

and the two js.erb pages:

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

The other:

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

I also already tried changing the variable in the week_before and after actions in the controller but it gives the same error 'nil cannot have operation "-"' or something, which just means it's not recognizing the variable.

dylanjack
  • 15
  • 2

1 Answers1

1

The way you have it coded now, the value of the @wbeg variable at the time the javascript file is generated will be hard coded into the javascript file. That value will never change. Whatever it was when the javascript was generated is it.

What you need is a javascript variable that you can update in the javascript code which makes the AJAX call.

Marlin Pierce
  • 9,931
  • 4
  • 30
  • 52
  • I couldn't figure out how to update and deal with javascript variables because I needed to be able to shift the @wbeg variable by 7 days at a time and converting it to javascript turns the variable into a string as opposed to a date in ruby. I eventually solved the problem by using ruby on rails sessions though. Thanks for the help. – dylanjack Jul 09 '18 at 22:33