Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

Rails assign instance variables in controller


I have the following in my controller:

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

I am trying to set each of those instance variables (@pwvav_ratings,@pwbab_ratings...) to the find if the find is not nil, so that I can call it in my view. How do I check if..or and if nothing is found, rescue with the flash notice.


Solution

  • Try this.

    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
    

    You can call .recomendation.split(',') on each variable in your view.