Built my first web application using Ruby
Gaming Review Zone (GRZ - Pronounced as Gears) is a simple website where you can create reviews about video games. As a gamer, I thought this concept for my first web app would be perfect!
The process
To keep it short and simple, Sinatra
is one of the web frameworks I used along with ActiveRecord
and SQLite
. To start my skeleton, I used the corneal
gem to generate the base of the application with all of my models, views, and controllers.
I populated the database with my users, reviews, and upvotes table and formed has_many
and belongs_to
relationships between them. I implemented authentication/authorization for log in, log out functions and confirming the users identity. I added all of the necessary routes to all 4 controllers (application, reviews, sessions, users) and the necessary html for my views.
.build
Method
The build
method was something that was confusing to me. After searching high and low for examples, I finally have an idea on what it does.
build
works the same as new
, the only difference is build
instantiates the object's associations while new
only instantiates the object. For example:
#tux
test = Review.new(game_title: "test", body: "test")
=> #<Review id: nil, user_id: nil, game_title: "test", body: "test", upvotes: nil, created_at: nil, updated_at: nil>
Notice how our user_id
is nil
@test = test.build_user(email: "test@test.com", username: "testy", password: "12345678")
=> #<User id: nil, email: "test@test.com", username: "testy", password_digest: "$2a$12$9AuPJRVMMaKCiNmHy7YUl.ncgA5YN5Cvj9lFhp/c1ho...">
Note: I'm using build_user
since this is a belongs_to
relationship and not a has_many
relationship. Using test.user.build
will give you a NoMethodError
If I do user.build_review(game_title: "test", body: "test")
I will get an NoMethodError
as well, but user.reviews.build(game_title: "test", body: "test")
will work since it's a has_many
relationship.
@test.save
=> true
@test
#<User id: 17, email: "test@test.com", username: "testy", password_digest: "$2a$12$w9Xx3M5/5pz57GKaOQl9e.WMTVZ2nKHsqDjoWWd6fCb...">
Note: build
only returns the created object without saving it.
Now they are associated. build
is just a neat way of associating your objects.
Overall
I had a few tweaks and hiccups, but altogether, working on the project wasn't as bad as I thought it would be. This is my second project, and since the first one, I've improved very much. I've spent more time working on cosmetics than the code itself, I've learned a lot, did tons of research, and had support to help me through the build.
I know there's still a lot to learn, but working on this project definitely opened my eyes a little. I feel proud of myself for sticking through and not giving up. I'm fully ready to upgrade to Rails!
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.