To begin, the button existed on the ingredients index page. Where the button will render, I created a partial to render an ‘Add’ or ‘Remove’ button depending on context.
In my partial there are some new things to account for. For one are the actions of each button. I knew I had to create both an
remove_from_bar in my Ingredients controller. Next, I’m using the
:class is for use with Bootstrap, basically it is making a green or red button for Add or Remove. Finally at the end
remote: true makes it possible for the button to be submitted via Ajax. This information (apart from the bootstrap tags) can be seen in the Ingredients controller:
add_to_bar method, we are creating a
bar_item by using the current
ingredient and adding to to the user’s bar items. After this saves, we use a
format.js response to render an action related to a
add_or_remove.js.erb file, along with a message we are passing that will help us render the flash notice. Inversely, the
remove_from_bar method is destroying the same
bar_item that we find by using the current
@ingredient, then destroying it. The message passed is now “Removed from bar” and we are rendering the same action as a result.
First, I used the
ingredient.id id attribute that was reference in the
_add_or_remove.html.erb partial to target the correct button. From here, that same partial is being rendered and will set change the button depending on whether or not the user added or removed the ingredient.
From here, things got a little more interesting. I spent a good deal of time figuring out how to get a flash notice to pop up as a result of an Ajax response. Apparently this doesn’t just happen like it does with the standard html response and refresh that was occurring before. I played around with this for a bit, but it seemed to involved complicated custom method calls in
Yay! I got the buttons working and a flash notice was now popping up to inform the user. The problem now was that the ingredients index view is longer and when a user scrolls down, they won’t necessarily see the flash notice that appears right below the navbar. To correct this, I targeted the container holding the noticed in css and gave it the property
_messages.html.erb I include an
unless statement that states that if the request is not coming from
Ingredient#index to render flash notices as usual. Then, in
index.html.erb I include another flash container but added the class attribute
ingredient-index-flash which I can then target in my CSS. This causes my styling to only impact the flash notice for the ingredients index view only, hooray!