Database Reference
In-Depth Information
Listing 10-27.
The HTML Code Snippet for Displaying the List of Friends
<div class="col-md-3">
<h3>Current Friends</h3>
<table class="table" id="following">
{{#following}}
<tr><td>{{firstname}} {{lastname}}</td><td><a href="#" id="{{username}}"
class="removefriend">Remove</a></td></tr>
{{/following}}
{{^following}}
No friends :(
{{/following}}
</table>
</div>
To search for users to follow, the user section of
App
contains a GET route /searchbyusername and passes in
a username value as part of the path. This route executes the
search_by_user_name
method found in
User
class,
showing the second part of Listing 10-28. The first part of the
WHERE
clause in the method returns users whose
username matches on a wildcard String value. The second part of the
WHERE
clause in the method checks to make sure
the users in the MATCH clause are not already being followed by the current user.
Listing 10-28.
The
searchbyusername
Route and
service
Method
# search for users / returns collection of users as json
get '/searchbyusername/:username' do
content_type :json
username=params[:username]
json :users => search_by_user_name(neo, request.cookies[graphstoryUserAuthKey],username)
end
# search by user returns users in the network that aren't already being followed
def search_by_user_name(neo,currentusername,username)
username=username.downcase+".*"
cypher = " MATCH (n:User), (user { username:{c}}) " +
" WHERE (n.username =~ {u} AND n <> user) " +
" AND (NOT (user)-[:FOLLOWS]->(n)) " +
" RETURN n.firstname as firstname, n.lastname as lastname, n.username as username"
results=neo.execute_query(cypher, {:c => currentusername, :u => username} )
results["data"].map {|row| Hash[*results["columns"].zip(row).flatten] }
end
The
searchByUsername
in
{PROJECTROOT}/app/public/js/graphstory.js
uses an AJAX request and formats the
response in
render SearchByUsername
. If the list contains users, it will be displayed in the center of the page under
the search form, as shown in Figure
10-9
. Otherwise, the response will display “No Users Found."
Once the search returns results, the next action would be to click on the “Add as Friend” link, which will call the
addfriend
method in
graphstory.js
. This performs an AJAX request to the
follow
route, which then calls the
follow
method
in the
User
class. The
follow
method in
User
shown in Listing 10-29 will create the relationship between
the two users by first finding each entity via the
MATCH
clause and then using the
CreateUnique
clause to create the
directed
FOLLOWS
relationship. Once the operation is completed, the next part of the query then runs a
MATCH
on the
users being followed to return the full list of followers ordered by the username.