Ask A Question

Notifications

You’re not receiving notifications from this thread.

Add to Favorites: using same controller/action and js.erb files for different views

TL asked in Rails

Chris I'm a new subscriber and I'm loving Go Rails. The content is really usefull for real-world applications.

After implementing the "Like" feature in my website, I came across a doubt that keeps popping up in my apps.

Let's say I have a Favorites Controller that responds with create.js.erb and destroy.js.erb.

It all works great, but then let's say I have a different view called "Favorites" like the one you have here (https://gorails.com/users/:user_id/favorites) and I want to add a link to remove from favorites there.

The difference is that, in this view, when I remove something from favorites, I want the video to disappear from the list, and not only the heart to become gray, so the jQuery in the js.erb response is different.

It sounds silly to repeat the controller code and views, so I assume we should keep things DRY and use the same controller and actions.

But the question is: how to deal with this scenario when the HTML for the js.erb response is different, since we're dealing with 2 different views?

Right now I'm solvin this by passing data: {params: {source: 'name_of_the_view} } in the link_to, and using that params[:source] in the js.erb to render the correct jQuery accordingly using if/else statements. Do you agree with this solution? Is there another best practice?

Reply

If you submit the delete request, you could have two different Javascript snippets run, one for each of the different interactions you want to have.

For example:

// Hide the favorite 
$("#favorite_<%= @favorite.id %>").hide()

// Make the item gray
$("[data-favorite-id=<%= @favorite.id %>][data-behavior='heart").removeClass("active")

This way your HTML can include the features you want on that page and the Javascript will modify whatever it finds on the page. I showed two different selectors you could use for this. I find using data-behavior to be particularly handy so you can have multiple pieces of functionality on the page for a single favorite and search for them easily.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.