Checking for nil in view in Ruby on Rails

后端 未结 5 655
故里飘歌
故里飘歌 2021-01-11 09:41

I\'ve been working with Rails for a while now and one thing I find myself constantly doing is checking to see if some attribute or object is nil in my view code before I dis

5条回答
  •  长发绾君心
    2021-01-11 10:14

    Your example code remade:

    controller code. ( I assume this is ItemsController )

    def show
      # This will fail with 404 if item is not found
      # You can config rails to pretty much render anything on Error 404
      @item = Item.find(params[:id])
    
      # doesn't seem to be used in the view
      # @folders = Folder.find(:all, :order => 'display_order')
    
    
      # this is not needed anymore, or should be in the Error 404 handler
      #if @item == nil or @item.folder == nil
      #  redirect_to(root_url) and return
      #end
    end
    

    view code, since the controller made sure we have @item

    #display the item's attributes here
    
    <%= item_folder_link(@item) %>
    

    helper code:

    # display link if the item has a folder
    def item_folder_link(item)
      # I assume folder.name should be a non-blank string
      # You should properly validate this in folder model
      link_to( item.folder.name, folder_path(item.folder) ) if item.folder
    end
    

    Anyway, I try to keep view very very simple. Usually if I see loops and conditionals in views, I try to refactor them into helpers.

提交回复
热议问题