查询在rails控制器中获取错误的值和NilClass

时间:2016-03-22 12:25:22

标签: ruby-on-rails ruby-on-rails-4

您好在下面的代码中虽然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

提前致谢。

0 个答案:

没有答案