0

I have Users (via devise) and Artists. A user can 'like' many artists. Artists are liked by many users.

I added a like/unlike button to my artist pages, based on code from an answer found on SO by @dwhalen: https://stackoverflow.com/a/6483109

The like/unlike works -- it updates the db. However, the button doesn't change on the webpage. I have to refresh the entire URL to see the 'like' turn to an 'unlike' button. In Chrome, the javascript console gives me a 404 error:

GET http://localhost:3000/likes/25 404 (Not Found) jquery.js?body=1:9667

Opening that in console gives:

send jquery.js?body=1:9667
jQuery.extend.ajax jquery.js?body=1:9212
$.rails.rails.ajax jquery_ujs.js?body=1:81
$.rails.rails.handleRemote jquery_ujs.js?body=1:157
(anonymous function) jquery_ujs.js?body=1:364
jQuery.event.dispatch jquery.js?body=1:4625
elemData.handle jquery.js?body=1:4293

I built everything with scaffolds, I am reading this maybe wasn't the best idea, but I don't know any better.

All my code is open and accessible here: https://github.com/stevepopo/playmycity Files of relevance I believe are 'likes_controller' (below), models/like.rb, views/likes/_form.html.erb & _like_button.html.erb & toggle.js.erb, and views/artists/show.html.erb (where the like/unlike div is).

I really don't know whether to copy all these files into this question -- it seems that link to my code should help you out?

The one bit of code I didn't use from the example I was basing off of was in 'likes_controller.rb'. Specifically:

@like = Like.create(params[:like])

Because I didn't know if that was the same as what was already in my code (somehow):

@like = Like.new(like_params)

Ditto for similar line under 'def destroy'.

His looks like:

class LikesController < ApplicationController

  # respond_to :js

  def create
    @like = Like.create(params[:like])
    @product = @like.product
    render :toggle
  end

  def destroy
    like = Like.find(params[:id]).destroy
    @product = like.product
    render :toggle
  end

end

In my code (below), I also question whether the 'format.html' response is screwing things up, prior to rendering :toggle. But I don't know, because that code was already there (scaffolds?).

Mine is:

class LikesController < ApplicationController
  before_action :set_like, only: [:show, :edit, :update, :destroy]

  # GET /likes
  # GET /likes.json
  def index
    @likes = Like.all
  end

  # GET /likes/1
  # GET /likes/1.json
  def show
  end

  # GET /likes/new
  def new
    @like = Like.new
  end

  # GET /likes/1/edit
  def edit
  end

  # POST /likes
  # POST /likes.json
  def create
    @like = Like.new(like_params)
    @artist = @like.artist

    respond_to do |format|
      if @like.save
        format.html { redirect_to @like, notice: 'Like was successfully created.' }
        format.json { render :toggle }
      else
        format.html { render :new }
        format.json { render json: @like.errors, status: :unprocessable_entity }
      end
    end

  end

  # PATCH/PUT /likes/1
  # PATCH/PUT /likes/1.json
  def update
    respond_to do |format|
      if @like.update(like_params)
        format.html { redirect_to @like, notice: 'Like was successfully updated.' }
        format.json { render :show, status: :ok, location: @like }
      else
        format.html { render :edit }
        format.json { render json: @like.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /likes/1
  # DELETE /likes/1.json
  def destroy
    @like.destroy
    @artist = like.artist

    respond_to do |format|
      format.html { redirect_to likes_url, notice: 'Like was successfully destroyed.' }
      format.json { render :toggle }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_like
      @like = Like.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def like_params
      params.require(:like).permit(:user_id, :artist_id, :listen_count, :play_my_city)
    end
end

All code is found: https://github.com/stevepopo/playmycity

Thank you for your help!

UPDATED: RAILS CONSOLE RESULTS Here's the rails console results asked by a commenter:

Started POST "/likes" for 127.0.0.1 at 2014-07-11 14:01:03 -0400
Processing by LikesController#create as JS
  Parameters: {"utf8"=>"✓", "like"=>{"artist_id"=>"1", "user_id"=>"1"}, "commit"=>"Like"}
  Artist Load (2.9ms)  SELECT  "artists".* FROM "artists"  WHERE "artists"."id" = ? LIMIT 1  [["id", 1]]
   (0.5ms)  begin transaction
  SQL (1.0ms)  INSERT INTO "likes" ("artist_id", "created_at", "updated_at", "user_id") VALUES (?, ?, ?, ?)  [["artist_id", 1], ["created_at", "2014-07-11 18:01:03.115390"], ["updated_at", "2014-07-11 18:01:03.115390"], ["user_id", 1]]
   (7.8ms)  commit transaction
Redirected to http://localhost:3000/likes/26
Completed 302 Found in 65ms (ActiveRecord: 12.2ms)


Started GET "/likes/26" for 127.0.0.1 at 2014-07-11 14:01:03 -0400

ActionController::RoutingError (No route matches [GET] "/likes/26"):
  actionpack (4.1.1) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  actionpack (4.1.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.1.1) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.1.1) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.1.1) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.1.1) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.1.1) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.1.1) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.1.1) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.1.1) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.1.1) lib/action_dispatch/middleware/static.rb:64:in `call'
  rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  railties (4.1.1) lib/rails/engine.rb:514:in `call'
  railties (4.1.1) lib/rails/application.rb:144:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
  /Users/steve/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/webrick/httpserver.rb:138:in `service'
  /Users/steve/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/webrick/httpserver.rb:94:in `run'
  /Users/steve/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/webrick/server.rb:295:in `block in start_thread'


  Rendered /Users/steve/.rvm/gems/ruby-2.1.2@global/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (5.8ms)
  Rendered /Users/steve/.rvm/gems/ruby-2.1.2@global/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb (25.1ms)

RAKE ROUTES INFO:

                  Prefix Verb   URI Pattern                        Controller#Action
          location_likes GET    /location_likes(.:format)          location_likes#index
                         POST   /location_likes(.:format)          location_likes#create
       new_location_like GET    /location_likes/new(.:format)      location_likes#new
      edit_location_like GET    /location_likes/:id/edit(.:format) location_likes#edit
           location_like GET    /location_likes/:id(.:format)      location_likes#show
                         PATCH  /location_likes/:id(.:format)      location_likes#update
                         PUT    /location_likes/:id(.:format)      location_likes#update
                         DELETE /location_likes/:id(.:format)      location_likes#destroy
                   likes POST   /likes(.:format)                   likes#create
                    like DELETE /likes/:id(.:format)               likes#destroy
               locations GET    /locations(.:format)               locations#index
                         POST   /locations(.:format)               locations#create
            new_location GET    /locations/new(.:format)           locations#new
           edit_location GET    /locations/:id/edit(.:format)      locations#edit
                location GET    /locations/:id(.:format)           locations#show
                         PATCH  /locations/:id(.:format)           locations#update
                         PUT    /locations/:id(.:format)           locations#update
                         DELETE /locations/:id(.:format)           locations#destroy
        new_user_session GET    /users/sign_in(.:format)           devise/sessions#new
            user_session POST   /users/sign_in(.:format)           devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)          devise/sessions#destroy
           user_password POST   /users/password(.:format)          devise/passwords#create
       new_user_password GET    /users/password/new(.:format)      devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format)     devise/passwords#edit
                         PATCH  /users/password(.:format)          devise/passwords#update
                         PUT    /users/password(.:format)          devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)            devise/registrations#cancel
       user_registration POST   /users(.:format)                   devise/registrations#create
   new_user_registration GET    /users/sign_up(.:format)           devise/registrations#new
  edit_user_registration GET    /users/edit(.:format)              devise/registrations#edit
                         PATCH  /users(.:format)                   devise/registrations#update
                         PUT    /users(.:format)                   devise/registrations#update
                         DELETE /users(.:format)                   devise/registrations#destroy
                 artists GET    /artists(.:format)                 artists#index
                         POST   /artists(.:format)                 artists#create
              new_artist GET    /artists/new(.:format)             artists#new
             edit_artist GET    /artists/:id/edit(.:format)        artists#edit
                  artist GET    /artists/:id(.:format)             artists#show
                         PATCH  /artists/:id(.:format)             artists#update
                         PUT    /artists/:id(.:format)             artists#update
                         DELETE /artists/:id(.:format)             artists#destroy
             pages_about GET    /pages/about(.:format)             pages#about
           pages_contact GET    /pages/contact(.:format)           pages#contact
                    root GET    /                                  artists#index
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • I suspect that the create likes may then trigger another action that is not in routes. Look at your rails console while you use the ajax control. You should see what actions are triggered. – Syl Jul 11 '14 at 17:58
  • @Syl I added rake routes, and the results in rails console when I click the 'like' button. Thanks for any help with what you see there. – Steve Poland Jul 11 '14 at 18:07
  • It is trying to render HTML instead of JSON in the POST. Try taking out the `format.html` line in your `create` action. – mccannf Jul 11 '14 at 20:50

0 Answers0