Timmy Von Heiss Timmy Von Heiss - 4 months ago 8
Ruby Question

using respond_to do |format| format.js to show a message inside of a modal after photo is favorited inside a modal?

The web user has a modal open with a picture showing, they click on:

photos/show.html.erb

<%= link_to favorite_photo_path("#{photo.id}"), method: :put do %>
<span class="glyphicon glyphicon-heart"></span>
<% end %>


The end goal is to keep the user inside of the modal, with a message shown inside of the modal, "You have successfully favorited this photo"... I am testing this out in the middle of the controller where I call
respond_to do...
However, when the glyphicon is clicked the model is updated however browser ends up stuck on
www.examples.com/photos/1/favorite


Routes

resources :photos do
match :favorite, on: :member, via: [:put, :delete]
end


PhotosController

def favorite
@photo = Photo.find params[:id]
if request.put?
response = current_user.favorite_photos.new(photo: @photo)
if !response.valid?
redirect_to :back, notice: response.errors.full_messages
else
response.save
respond_to do |format|
format.js
end
end
else request.delete?
current_user.favorites.delete(@photo)
redirect_to :back, notice: 'You successfully unfavorited this photo'
end
end


photos/favorite.js.erb

$('.modal-dialog.photo>.message').html('You have successfully favorited this photo');


When html { redirect_to :back } is used, it closes the modal.

Answer

To utilize the JavaScript response, you will need to add the remote: true option to your link.

http://guides.rubyonrails.org/working_with_javascript_in_rails.html

If you want to handle this via AJAX, don't use redirect back.

Instead handle both scenarios in you're JavaScript file.

<% unless flash[:notice] %>
   $('.modal-dialog.photo>.message').html('You have successfully favorited this photo')
<% else %>
   $('.modal-dialog.photo>.message').html('<%= j flash[:notice] %>')
<% end %>
Comments