Loading usernames with AJAX - Rails

I use this gem: https://github.com/ichord/jquery-atwho-rails

Inside my controller:

@usernames = User.pluck(:username).compact

In my view:

<script>

data = <%= raw User.pluck(:username).compact %>; 
$('textarea').atwho({at:"@", 'data':data});

</script>

This is obviously a very dangerous and not very good idea. But for someone who has no AJAX or Javascript experience, how can I use this gem and use usernames efficiently through AJAX?

+4
source share
1 answer

You can use the callback remote_filter:

$('#textarea').atwho({
        at: "@",
        show_the_at: true,
        callbacks: {
            remote_filter: function(query, callback) {
                // Return false on empty query
                if (query.length < 1) {
                    return false
                }
                // AJAX call to http://yoursite/users.json?q=query
                $.getJSON("/users.json", {q: query}, function(data) {
                    callback(data.usernames)
                });
            }
        }
    })

> "q" ( ) /users.json. :

# controllers/users_controller.rb
def index
  respond_to do |format|
   format.json{ render :json => User.where('username like ?', "#{q}%").pluck(:username).compact}
  end
end

> : https://github.com/ichord/At.js/wiki/How-to-use-remote_filter

+1

Source: https://habr.com/ru/post/1533000/


All Articles