Question

I am trying to display some info from an API.

I have this code:

<% recco = Model.find_by_id(activity.trackable.id %>

Now, rendering the following line will output the ID I want:

<%= recco.item_id %>

However, when I want to link to this item and I need the name from the API, some of the code fails and some not. This is the line I have:

<%= link_to @client.author(recco.item_id).name, book_path(recco.item_id) %>

The book_path works and displays a link to the correct URL with the ID. The client that tries to get the name from the API returns that it is not found.

But, if I try remove the the recco.item_id and just hardcode it to:

<%= link_to @client.author("7").name, book_path(recco.item_id) %>

It works and displays the author name. Is there a special reason for the API request to not understand that the recco.item_id is a number? The book_path displays the link just fine.

Was it helpful?

Solution

It looks like the author method expects a string instead of an integer. All you have to do is add to_s to the item_id for it to work:

<%= link_to @client.author(recco.item_id.to_s).name, book_path(recco.item_id) %>

The reason why the API does not understand the integer you passed to it is likely because they did not logic have in that method to convert that passed argument into a string. Ideally, a public would try and convert whatever args are passed to it into the type of value it expects. The to_s we did on your method would ideally be in the API, but since you likely don't have control over the API code, you'll have to do the workaround yourself which doesn't take much effort anyway. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top