DEV Community

Brittany
Brittany

Posted on

Day 82 : #100DaysofCode - Received Help and Problem Solved

Today was a good day. I woke up this morning and had a meeting with someone who helped me move forward on an issue that I was struggling with:

The individual who helped me asked to remain anonymous and spent time showing me how to iterate through the Unsplash gem and displaying it using Javascript instead of Ruby.

First we saved the response from the Unsplash gem into a variable in the photos controller:

@photos = Unsplash::Photo.search("cats")

Then within the views, we iterated through the response to get what we needed. (please note, I definitely plan to move all the logic from my views into a helper when I am refactoring)
In addition, we added a class to the checkbox and an id to the submit button so that we could reference it with an eventListener in javascript/jquery.

 <% @photos.each do |p| %>
            <img src="<%= p["urls"].full %>" alt="random" ><br>
            <div><p> <%= p["alt_description"] %> </p></div><br>
            <%= check_box_tag "data", 1, false, data: {url: p["urls"].full, description: p["alt_description"]}, class: "add-photo"  %>
    <% end %>
  <button id="submit"> Submit </button>
Enter fullscreen mode Exit fullscreen mode

Within the application.js we added an initial function that will run on load. We added a click eventListener on the add-photo class and saved the url and description into an array.

$(document).on("turbolinks:load", function() {
    const photos = []
    $( ".add-photo" ).click(function(e) {
        const photo = {url: e.target.dataset.url, quote: e.target.dataset.description }
        photos.push(photo)
    });
Enter fullscreen mode Exit fullscreen mode

Then we added a click eventListener on the submit button which saved the photos object into a hash and made a fetch post request to /photos.

    $("#submit").click(function(e){
    fetch('/photos', {
        method: 'POST', // or 'PUT'
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({data: photos}),
        })
        .then(response => response.json())
        .then(data => {
        console.log('Success:', data);
        })
        .catch((error) => {
        console.error('Error:', error);
        });
    })
})
Enter fullscreen mode Exit fullscreen mode

I put a byebug in my create method within my photos controller and IT WORKED. I had all the information I needed to proceed with my project.

I am so grateful for their help and I know I would not have been able to proceed with my project anytime soon without their help.

I am happy that I learned something new and it made me excited to continue to learn with my bootcamp as I move on to Javascript next week.

I will continue with this project this weekend with high hopes to finish it by Sunday.

As always, thank you for reading!

Sincerely,
Brittany

Song of the Day:

Top comments (0)