Load more user movies via AJAX in rails

Viewed 733

I have a search movies application (Rails 4) and in 'my_movies' page I'm trying to show 2 user movies on page load and then after clicking a link 'Load More' other 2 ones.

Now I get 500 (Internal Server Error) with this code. I think I have problems in my controller. What I'm doing wrong?

models/user.rb

class User < ActiveRecord::Base
  has_many :movies, dependent: :destroy
end

models/movie.rb

class Movie < ActiveRecord::Base
  belongs_to :user
end

controllers/users_controller.rb

class UsersController < ApplicationController
  before_action :authenticate_user!
  after_action :verify_authorized

  def my_movies
    authorize :user, :my_movies?
    if params[:id]
      @user_movies = current_user.movies.where('id < ?', params[:id]).limit(2)
    else
      @user_movies = current_user.movies.limit(2)
    end
    respond_to do |format|
      format.html
      format.js
    end
  end
end

views/users/my_movies.html.slim

.row
  .small-12.columns.block.movies_container
    = render 'users/user_movies'

.row
  .small-12.columns.block.load_more_container
    = image_tag 'spinner.svg', style: 'display: none;', class: 'loading_icon'
    = link_to 'Load More', my_movies_user_path, class: 'load_more'

views/users/_user_movies.html.slim

- @user_movies.each do |movie|
  h2.user_movie data-id='#{movie.id}'
    = link_to movie.title, movie_path(movie)

views/users/_user_movies.js.slim

| $('.movies_container').append('
= escape_javascript(render(partial: 'users/user_movies'))
| ');

js/user.coffee

# when the page is ready for manipulation
$(document).ready ->
# when the load more link is clicked
  $('a.load_more').click (e) ->
# prevent the default click action
    e.preventDefault()
    # hide load more link
    $('.load_more').hide()
    # show the loading icon
    $('.loading_icon').show()
    # get the last id and save it in a variable 'last-id'
    last_id = $('.user_movie').last().attr('data-id')
    # make an ajax call passing along our last users movie id
    $.ajax
      type: 'GET'
      url: $(this).attr('href')
      data: id: last_id
      dataType: 'script'
      success: ->
        # hide the loading icon
        $('.loading_icon').hide()
        # show our load more link
        $('.load_more').show()
        return
    return
  return

Screenshot of the error:

enter image description here

UPD: After restarting Rails AJAX works fine, but I get doubled movies (the same are shown), instead of getting 2 others from database.

The error starts from here (2) and maybe here (1), because I sent user id's and not his last movie id.

enter image description here

Here is the console logs when the XHR starts:

enter image description here

How it can be fixed?

P.S. You can find this app here in GitHub, feature branch 'Loading more'.

1 Answers
Related