0

I'm trying to build a simple page that searches for github users and displays their followers on the page without refreshing the page. I'm using Octokit to access the Github api and Gon to create controller variables that can be accessed in js.erb files. I can access a gon variable that is set to a string, but not one that references the query params. How would I do this?

class UsersController < ApplicationController
  def search
    github = Octokit::Client.new(:login => 'monzelb', :password => "#{Rails.application.secrets.github_key}")
    @query = params[:query]
    gon.query = @query
    @followers = github.followers("#{@query}")
    gon.followers = @followers
    @blah = "blah"
    gon.blah = @blah
    if @query
      respond_to do |format|
        format.js 
        format.html 
      end
    end
  end
end

users/search.js.erb

console.log(gon.followers.first.login) # => nil
console.log(gon.blah) # => "blah"
$('body').append('<li class="result media"><%= j @followers.first.login %></li><img src= "<%= j @followers.first.avatar_url %>" class="result img">');

The jquery successfully appends the first follower's image and name to the page when the form is submitted, but I need to append ALL of their followers to the page. I thought Gon would be a good way to do this, but it doesnt seem to have access to the query.

Brett
  • 49
  • 2
  • 8

2 Answers2

0

I dont' know Js, Gon, or Octokit so I am not sure this answer will help you.

Yet you say that you see only the first follower appended. But this is completely normal. This is what your JS does:

$('body').append('<li class="result media"><%= j @followers.first.login %></li><img src= "<%= j @followers.first.avatar_url %>" class="result img">');

You can try a solution in Ruby maybe, like:

<% @followers.each do |follower| %>
$('body').append('<li class="result media"><%= j follower.login %></li><img src= "<%= j follower.avatar_url %>" class="result img">');
<% end %>

Not sure if this is going to work. But in any case this can probably be done in JS instead of Ruby...

Maxence
  • 2,029
  • 4
  • 18
  • 37
0

I'm not sure why you are doing this:

@query = params[:query]
gon.query = @query
@followers = github.followers("#{@query}")
gon.followers = @followers
@blah = "blah"
gon.blah = @blah

Instead you should be saving your @query, @followers, and @blah instance variables and then pushing them to gon.

So something like this:

gon.push({
   query: @query,
   followers: @followers,
   blah: @blah
})
jdgray
  • 1,863
  • 1
  • 11
  • 19