我在 RoR 甚至网络编程方面都是初学者。所以我想我的问题对于很多开发者来说都很简单!
我正在实现简单的周日历,它应该有日期的名称和两个“按钮”-“下周”和“上一周”。这就是开始!
我有带有索引操作的 Controller :
def index
@today = Date::today
@monday = @today.beginning_of_week
@sunday = @today.end_of_week
@currentweek = @monday..@sunday
end
以及另外两个操作:
def go_next_week
@monday = @sunday + 1
@sunday = @monday.end_of_week
end
def go_prev_week
@sunday = @monday - 1
@monday = @sunday.beginning_of_week
end
索引 View 代码:
<div class="wrapper">
<table class="data">
<thead>
<tr class="month-names">
<td><%= form_tag(work_days_go_prev_week_path, method: "get") do %>
<%= submit_tag(l(("workdays_show_prev" + period).to_sym)) %>
<% end %>
</td>
<td><%= render :partial => 'days_names_header' %></td>
<td><%= form_tag(work_days_go_next_week_path, method: "get") do %>
<%= submit_tag(l(("workdays_show_next" + period).to_sym)) %>
<% end %>
</td>
</tr>
</thead>
</table>
</div>
以及路线文件:
RedmineApp::Application.routes.draw do
match 'work_days/go_next_week' ,:to => 'work_days#go_next_week', via: [:get]
match 'work_days/go_prev_week' ,:to => 'work_days#go_prev_week', via: [:get]
match 'work_days/(:action(/:id))',via: [:get], :controller => 'work_days'
end
短期内该阶段的主要目标是:
Controller 有一个日期变量“星期一”、“星期日”和范围 “当前周”
索引 View 根据变量显示天数表
索引 View 有 2 个“按钮”:“下周”和“上周”
单击此按钮应更改 Controller 的变量
索引 View 应使用更改后的 Controller 变量“刷新”
该代码不起作用。单击“上个月”按钮时,我在日志中收到此类错误:
Started GET "/work_days/go_prev_week?tf8=%E2%9C%93&commit=Previous+week" for 127.0.0.1 at 2015-12-09 14:00:27 +0600 Processing by WorkDaysController#go_prev_week as HTML Parameters: {"utf8"=>"✓","commit"=>"Previous week"} Current user: admin (id=1) Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.2ms)
NoMethodError (undefined method `-' for nil:NilClass)
最佳答案
I'm very beginner in RoR and even in web-programming.
欢迎!
您的问题是您正在使用相互依赖的 @instance_variables
填充 Controller 操作:
def go_next_week
@monday = @sunday + 1 # needs @sunday
@sunday = @monday.end_of_week # needs @monday
end
在老式编程中,这可能会导致无法识别的引用错误或堆栈溢出错误,通常是由于无限 recursion .
错误证实了这一点:
undefined method `-' for nil:NilClass
Ruby
与大多数其他语言不同,它将未声明的变量分配给 NilClass
对象。这使得开发人员很难确定错误 - 基本上,如果您收到 NilClass 的未定义方法
,则表明您尚未声明变量。
--
解决方法是将您尝试操作的数据获取到类的实例中。这可以通过 before_action
来实现过滤器:
#app/controllers/work_days_controller.rb
class WorkDaysController < ApplicationController
before_action :set_dates
def index
#@today, @monday, @sunday will be available in here.
end
private
def set_dates
@today = Date::today
@monday = @today.beginning_of_week
@sunday = @today.end_of_week
end
end
您还可以改进您的路线以利用 resources
指令:
#config/routes.rb
resources :work_days do
get :go_next_week, on: :collection
get :go_prev_week, on: :collection
end
关于ruby-on-rails - ruby 在 rails 上。通过 View 更改 Controller 的变量并渲染更新的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34173671/