Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

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

Rails • Asked by TL

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 ( 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?

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_<%= %>").hide()

// Make the item gray
$("[data-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.

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 31,575+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.