Rails在控制器中分配实例变量

时间:2013-03-06 18:51:55

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我的控制器中有以下内容:

if params[:option] == "1"
      id = params[:id]
      @resultsReceived = true
      begin
       @pwvav_ratings = Pwvav.find_by_id(id).recommendation.split(",")
      #or
       @pwbab_ratings = Pwbab.find_by_id(id).recommendation.split(",")
     #or
       @puvub_ratings = Puvub.find_by_id(id).recommendation.split(",")
     #or
       @tic_ratings   = Tic.find_by_id(id).recommendation.split(",")
     rescue
       redirect_to "/view_api", :flash => { :notice => "Sorry, No records returned for #{id}." }
      end

我试图将每个实例变量(@pwvav_ratings@pwbab_ratings ...)设置为find,如果find不是nil,那么我可以在我的视图中调用它。如何检查是否..或如果找不到任何内容,请使用闪光灯通知进行救援。

2 个答案:

答案 0 :(得分:0)

将此添加到每行的末尾。验证它不是零。 (请注意!,但您也可以使用not

@pwvav_ratings = Pwvav.find_by_id(id).recommendation.split(",") if !Pwvav.find_by_id(id).recommendation.split(",").nil?

或者您可以使用unless

@pwvav_ratings = Pwvav.find_by_id(id).recommendation.split(",") unless Pwvav.find_by_id(id).recommendation.split(",").nil?

答案 1 :(得分:0)

试试这个。

if params[:option] == "1"
  id = params[:id]
  @resultsReceived = true
  @pwvav_ratings = Pwvav.find_by_id(id)
  #or
  @pwbab_ratings = Pwbab.find_by_id(id)
  #or
  @puvub_ratings = Puvub.find_by_id(id)
  #or
  @tic_ratings   = Tic.find_by_id(id)
  unless @pwvav_ratings || @pwbab_ratings || @puvub_ratings || @tic_ratings
    redirect_to "/view_api", :flash => { :notice => "Sorry, No records returned for #{id}." }
  end
end

您可以在视图中的每个变量上调用.recomendation.split(',')