Table of Content
Before protecting uploading, we need to add the association between the user and the albums/photos.
Execute the following migration generation commands and migrate the database.
$ rails generate migration AddUserIdToAlbum user_id:integer $ rails generate migration AddUserIdToPhoto user_id:integer $ rake db:migrate == AddUserIdToAlbum: migrating =========================== -- add_column(:albums, :user_id, :integer) -> 0.0016s == AddUserIdToAlbum: migrated (0.0018s) ================== == AddUserIdToPhoto: migrating =========================== -- add_column(:photos, :user_id, :integer) -> 0.0009s == AddUserIdToPhoto: migrated (0.0011s) ==================
belongs_to :user to both
album.rb class and
And the following to
Next, we would like to protect user upload in the photos controller.
And we add the user association
@photo.user = current_user in the create method.
Now when we go to any photo upload URL without logged in to the album owner, we will be redirected to the sign_in page.
Then we apply the same to the albums controller.
And the user-albums association in the
Note: If both `authenticate_user` share the same logic, we can further extract it into their common parent class — application_controller.
It’s time to test the function in web browser.
We can create albums and upload photos as normal after we logged in. Now try to create another user account and access the album you just created, you should not be able to upload any new photos.
One last thing, we don’t want the
upload photo or
edit link appears on the photo that isn’t belonged to the current user.
What’s next? We’re going to take a look at “Challenges”.