Tag Archives: ruby

Following, Friending, and Lending: Self-Referential Associations with Rails

Published by:

Self-Referential Associations happen when you connect a table back into itself in Active Record. This is commonly found in a Following function, where one User follows another. As a new Rails developer, the first time I tried these was somewhat daunting, but I managed to pull off both Following and Lending in my app. I used a helpful Rails Cast and various Google searches to figure this out.

This post assumes that you have already setup authentication in your app and have some way of referencing the logged in user (referred to as “current_user”). I have my Solution and a Starter in this github repo, both have authentication that only requires the username to login.

Start by thinking about what your associations–what are you connecting? For basic Following (in the manner of Twitter’s following feature), you are just connecting two users. Therefore, you need a join table with has_many through in your model.

Setup the join table:

Here you reference one user, but then need a way to reference a second user without interference. In this case, I use “followed” to refer to the other user–they’re the ones being followed.

t.integer :user_id
t.integer :followed_id

You do not need to touch the Users table, since we’re using a join table. Then migrate this new table to add it to your database.

Now that you have the table, you should set up the route:

resources :follows

That’s it. You can nest it with users if you’d like, and then change the rest of the code to suit.

Next setup the Follow model. This is where we show that the “followed” is actually a User:

belongs_to :user
belongs_to :followed, :class_name => “User”

In the User model, we also need to setup associations. Since we have two users in everything we do, we need two sets of references here. The user has many follows (for the follow table) and has many followed through follows (they can follow many users). But they also can be followed. Here I used “inverse” to show the second relationship, which seemed to be the way others online were solving this issue.

has_many :follows
has_many :followed, :through => :follows
has_many :inverse_follows, :class_name => “Follow”, :foreign_key => “followed_id”
has_many :followers, :through => :inverse_follows, :source => :user

So: A user has many entries in the follows table, which connect them to the people they followed. A user also has many entries in the follows table of people who are their followers.

This is a good time to setup a Follows controller, as well, with an empty class.

Since this is a self-referential association with Users, I put the actual method for following in the Users model.

def follow(other_user)
if self.followed.include?(other_user)
return false
else
self.follows.create(:followed_id => other_user.id)
return true
end
end

This is a method called “follow” which takes in other_user (a variable I’ll be defining in the controller) and after checking to make sure they’re not already following that person, I create an entry in the follows table referencing the user the current user wants to follow.

Now I go back to the Follows controller and set up the create method. We don’t need “new” because we’re not using any views.

def create
@user = User.find(params[:followed_id])
if current_user.follow(@user)
flash[:notice] = “Followed user.”
redirect_to current_user
else
flash[:error] = “Unable to follow user.”
redirect_to current_user
end
end

This takes the params and sends it to the follow method (@user becomes other_user). If the follow method works (if the user isn’t already following them), they are given an announcement saying they followed them and then redirected to their own page. If it doesn’t work, they are given an error and redirected.

Since people should be able to unfollow, as well, you set up a destroy:

def destroy
@follow = current_user.follows.find(params[:id])
@follow.destroy
flash[:notice] = “Stopped following user.”
redirect_to current_user
end

Basically, you’re just destroying the entry in the follows table associated with that id.

Now for another difficult part, the views. This is where the links will go that allow users to follow each other. This can be hard to visualize how it’s supposed to happen, if you’re not using a specific follow view.

In the Users index, I put a list of the Users:

<h1>Users:</h1>
<% for user in @users %>
<p>
<strong><%= link_to user.username, user_path(user) %> </strong>
<small><%= link_to “Follow”, follows_path(:followed_id => user), :method => :post %></small>
</p>
<% end %>

In the Users show page, I put a list of each user’s followeds and followers.

<h2>User: <%= @user.username %></h2>
<h3>Followers:</h3>
<ul>
<% for user in @user.followers %>
<li><%=h user.username %></li>
<% end %>
</ul>
<h3>Following:</h3>
<ul>
<% for follow in @user.follows %>
<li>
<p><%=h follow.followed.username %>(<%= link_to “remove”, follow, :method => :delete %>)</p>
</li>
<% end %>
</ul>

Other things you can do: Create friendships, where relationships have to be mutual to show up, or create lending features, where you connect another model and have one user lend something they own to another. For an example, check out what I did with Loans in this project.

I’m happy to answer questions, too.

You may have possibly sunk a Battleship at some point

Published by:

Last week, Week 3, was our first project week. I was out sick with a bad cold on Tuesday, when they were assigned, and scrambled on Wednesday to catch up. Out of three projects, I was given Battleship. Or, creating a Ruby program for a command line Battleship game. It was generally accepted to be the hardest of the projects and just seeing the directions were overwhelming at first.

Deciding on what type of grid I would use for the board was my first step. It took way too long, but I felt that I had to have the board setup before I could hope to do anything else, since so much would rely on it. Finally, I decided on a one-dimensional array, which I would print out on the screen for people to view. I think it was the simplest method to use and it made finding the actual hits and misses very easy.

The grid printed out the coordinates, as well, and players could just type in the grid location, like you would say in a real life Battleship game, “A1,” “B2,”.

From there, I had to build up the game itself, using While loops and If/Elsif to go through the motions of every possibility that might come up. I created a game table in ActiveRecord, with ships, players, and turns as subtables. Since ActiveRecord isn’t the biggest fan of arrays, separating turns into their own rows and then turning them back into an array later on seemed like a better choice.

It was a harrowing experience, but after the fact it was a great learning opportunity. The fact there were so many ways to go about making the Battleship game meant that it was next to impossible to fall back on anyone else for help, unlike with many past homework experiences where we were able to work basically in a group. So, while it is very important for coding to have experience working with others, it was good to spread my wings and have to rely basically on myself.

(Coincidentally, on Thursday afternoon our class took a fieldtrip to USAToday and part of the presentation we were given involved slides where the person who created them used Battleship as a metaphor. Since most of us were desperate to get done by Friday morning, we shared a slightly hysterical chuckle.)

Difficulties:

The necessity to use ActiveRecord to save game information–not just players and scores, but the actual ship locations and previous turns–so people could restart them made things unnecessarily difficult in my opinion. While it was necessary for what we were learning and trying to practice at the time, in a real life situation I feel it’s unlikely anyone would want to restart their Battleship game partway through, as opposed to just starting a new game each time.

Things I wish I’d gotten to:

Changing the places on the grid to reflect a hit or miss (I had started, but had to trash that code because I couldn’t get it to work). Making it look nicer (I had tried to design all my own text art, but realized after the fact I should have just used a website). Adding a two player option (again, something I started, but didn’t get to finish). Separating the game out into more methods, so it’s more compartmentalized and would be easier to switch between single player and two player games.

I also was wondering about how much time this would take in a larger app, how many bits I was taking up that might be a constraint with something else.

You can find my most recent work on the game on Github.