我正在使用Rails 4.2.3。在我的“app / controllers / user_objects_controller.rb”控制器文件中,我已经定义了这个方法......
def find_totals
respond_to do |format|
@current_user = User.find(session["user_id"])
format.json {
@month_total = UserObject.find_total_by_user_object_month_and_year(session["user_id"], params[:object], params[:month], params[:year])
@year_total = UserObject.find_total_by_user_object_and_year(session["user_id"], params[:object], params[:year])
render :json => {:month => @monthTotal,
:year => @yearTotal }
}
end
end
我正在尝试使用Ajax来调用此方法,因此在我的“./app/assets/javascripts/user_objects.js.coffee”脚本中,我有
updateTotal = (arg) ->
object = $('#user_object_object').val()
date = $("#datepicker").datepicker('getDate')
day = $('#user_object_day').val()
month = date.getMonth() + 1
year = date.getFullYear()
if (object != "" && day != "")
# Populate the month and year totals
$.ajax
url: "/user_objects/find_totals"
type: 'GET'
data: {month: month, year: year, object: object}
success: (data) ->
alert(data);
$('#month_total').val(data)
$('#year_total').val(data)
error: ->
alert "Something went wrong getting month and year total"
但我总是得到错误条件。在我的Rails服务器中,打印下面的日志:
D, [2016-02-24T15:42:24.475092 #12929] DEBUG -- :
D, [2016-02-24T15:42:24.475206 #12929] DEBUG -- :
D, [2016-02-24T15:42:24.475236 #12929] DEBUG -- :
D, [2016-02-24T15:42:24.475265 #12929] DEBUG -- :
I, [2016-02-24T15:42:24.475505 #12929] INFO -- : Started GET "/user_objects/find_totals?month=2&year=2016&object=3" for 127.0.0.1 at 2016-02-24 15:42:24 -0600
I, [2016-02-24T15:42:24.475539 #12929] INFO -- : Started GET "/user_objects/find_totals?month=2&year=2016&object=3" for 127.0.0.1 at 2016-02-24 15:42:24 -0600
F, [2016-02-24T15:42:24.500710 #12929] FATAL -- :
ActionView::Template::Error (undefined method `object' for nil:NilClass):
2:
3: <p>
4: <strong>object:</strong>
5: <%= @user_object.object %>
6: </p>
7:
8: <p>
app/views/user_objects/show.html.erb:5:in `_app_views_user_objects_show_html_erb__2677150194333288712_70363943163180'
F, [2016-02-24T15:42:24.500751 #12929] FATAL -- :
ActionView::Template::Error (undefined method `object' for nil:NilClass):
2:
3: <p>
4: <strong>object:</strong>
5: <%= @user_object.object %>
6: </p>
7:
8: <p>
app/views/user_objects/show.html.erb:5:in `_app_views_user_objects_show_html_erb__2677150194333288712_70363943163180'
任何人都知道这个错误意味着什么以及如何解决它?
答案 0 :(得分:0)
未定义的方法`对象&#39;为零:NilClass
表示此处@user_object
<%= @user_object.object %>
是零。这是有道理的,因为@user_object
无法在控制器方法/操作中找到def find_totals
您需要在控制器的某个位置设置该实例变量,以便在您的视图中为您提供
答案 1 :(得分:0)
@user_object是零。
未定义的方法`对象&#39;为零:NilClass
答案 2 :(得分:0)
看起来Rails正在尝试渲染show.html.erb,这意味着ajax请求正在点击UserObjects控制器上的show动作,这表明路径不正确。
检查您的路线文件。路由按照指定的顺序进行匹配,因此如果您在resources :user_objects
之前有get "user_objects/find_totals" ...
,则Rails会认为&#34; user_objects / find_totals&#34; URL与UserObjects控制器上的show动作匹配,ID为find_totals
。