您好在下面的代码中虽然where
方法中的create
查询即变量@count_of_fav_texts_present
在rails控制台中获取1条记录,但在控制器中@count_of_fav_texts_present
的值是零并进入第一个if
子句。
同样在内部if
子句中,find_by
即变量var_fav_text
的查询给出了NilClass。虽然当我在控制台中检查它时,值不是Nil,并且它有一条记录。
我对Rails很新,我不确定我犯的是什么错误。请帮忙。
class NewfavoriteTextsController < ApplicationController
before_action :set_text
before_action :set_favgroup
before_action :authenticate_user!
def create
@count_of_fav_texts_present = Favorite.where(favorited_id: @text_id, user_id: current_user.id).count
if @count_of_fav_texts_present == 0
if Favorite.create(favorited: @text, user: current_user)
if Newfavorite.create(favorite_group_id: @fav_group, newfavorited: @text)
var_fav_text = Favorite.find_by(favorited_id: @text_id, user_id: current_user.id)
cnt_of_var = var_fav_text.counter
var_fav_text.counter = cnt_of_var + 1
var_fav_text.save
else
# do something
end
else
# do something
end
else
# for condition when var is greater than 0
if Newfavorite.create(favorite_group_id: @fav_group, newfavorited: @text)
var_fav_text = Favorite.find_by(favorited_id: @text_id, user_id: current_user.id)
cnt_of_var = var_fav_text.counter
var_fav_text.counter = cnt_of_var + 1
var_fav_text.save
else
# do something
end
end
end
def destroy
# do something
end
private
def set_text
@text = Text.find(params[:text_id] || params[:id])
end
def set_favgroup
@fav_group = params[:fav_group_id]
end
end
提前致谢。