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

Ruby on Rails proper way to add a favorite button for front end


So far I have two tables User and Company. Users are able to favorite many companies. I established all the back end code to add favorites (a join table with many to many relationship) I also have a general setup to add favorites.

I need some help with the front end side though.

So far what I have is a search page where users can query a company ticker to get companies. I display it like the following

<% if @results %>
  <h4>Search results for <%= @symbol %></h4>
  <table>
    <tr>
      <th>ID</th>
      <th>Symbol</th>
      <th>Name</th>
    </tr>

    <% @results.each do |res| %>
      <tr>
        <td><%= res.id %></td>
        <td><%= res.symbol %></td>
        <td><%= res.name %></td>
        <td><%= link_to "Favorite", create_favorite_path(current_user.id, res.id), method: :post, :remote => true %></td>
      </tr>
    <% end %>
  </table>
<% end %>

Right now I have a "favorite button" implemented with

<td><%= link_to "Favorite", create_favorite_path(current_user.id, res.id), method: :post, :remote => true %></td>

It seems messy and I dont think this is right. I also want to add a few more features

  • I want to know if the post method was successful or not
  • Based on the post, I want to be able to change the button text to something like "saved"
  • later change the link to have a star button icon

I would love suggestions to improve this and do it properly


Solution

  • I prefer using a front-end framework to handle things like this. They allow the components to be much more dynamically interactive.

    re: I want to know if the post method was successful or not in the absence of a front-end framework you can catch failed save in the favorites_controller and add a flash[:error] to the page.

    flash[:errors] = @favorite.errors.full_message unless @favorite.save!

    re: Based on the post, I want to be able to change the button text to something like "saved" You can use jQuery to change the button CSS on click of the favorite button.

    <% if @results.favorited? %>
    # render button with favorited class (with star)
    <% else %>
    # render button without favorited class (without star)
    <% end %>