Search code examples
ruby-on-railsrubyundefinednomethoderror

Best way to fix undefined method


I am building a rails app where I have a museums page which has a feature where it displays the museum with the most exhibits. The problem is that when there are no exhibits added to the db it gives an undefined method 'museum_name'. So the problem I have is I am not sure what would be the best way to make a check that would still allow me to access the page if there are zero exhibits?

Museums controller:

def index
   @museums = Museum.all
   most_exhibits = Exhibit.most_exhibits
   most_exhibits.each do |museum|
   @top_museum = MuseumsHelper.get_museum_name(museum.museum_id)[0]
end

Helper class method being used:

  def self.get_museum_name(museum_id)
    Museum.where(id: museum_id)
  end

Display in views:

<%= @top_museum.museum_name %>

Solution

  • The best way to do it depends on how you want it to be. I think the ideal solution for yours is to check if/else then show the content accordingly:

    <% if @top_museum.present? %>
      <%= @top_museum.museum_name %>
    <% else %>
      <span>Nothing to display</span>
    <% end %>
    

    Or using try <%= @top_museum.try(:museum_name) %> or if you have ruby 2.3.0 or newer you can use safe navigation operator <%= @top_museum&.museum_name %> (Read more).