Search code examples
ruby-on-railsrubyruby-on-rails-4link-to

Nil param value is causing a crash. How do I only create a param if the value I'm setting it with exists?


Here is my code:

 <% @garments.each do |garment| %>
   <tr>
     <td>
       <div>
        <%= link_to "Edit", edit_adminpanel_path(
         :id => garment["objectId"], 
         :image => garment["image"].url, 
         :image2 => garment["image2"].url, 
         :image3 => garment["image3"].url, 
         :image4 => garment["image4"].url, 
         :image5 => garment["image5"].url, 
         :image6 => garment["image6"].url) 
        %>
       </div>

As you see I'm creating params and setting them with the image url of images. However an object won't always have 6 images. Some may have 2 some may have 3 some may even have just 1 image. The call to nil properties will cause my app to crash.

I tried to add if statements at the end of each line before the comma but this doesn't work. How can I safely check if an object image exists and only then create and set it's corresponding params value?

Originally I tried passing the whole object as a param but ran into problems in my other controller. So for now I'd like to pass the image URL's separately.

Thanks for your time


Solution

  • You can build it dynamically, by adding only values that exist:

    <% path_params = %w(image image2 image3 image4 image5 image6).each_with_object(:id => garment["objectId"]) do |name, hash|
      hash[name.to_sym] = garment[name].url if garment[name]
    end %>
    <%= link_to "Edit", edit_adminpanel_path(path_params) %>