Reflection to Tealeaf Course3 Week6 (1/2)
These week we have two main part: CarrierWave for uploading images as an admin, Stripe for payments
#CarrierWave for uploading images as an Admin
###Admin
In order to controll user is a admin or not, the best practice is to build a admin its own self routes and controllers.
In routes.rb
1 | namespace :admin do |
Then rake routes
, we got
1 | admin_todos admin/todos admin/todos#index |
Build the controller file in the path: /controllers/admin/todos_controller.rb
1 | class Admin::TodosController < ApplicationController |
It’s aother rails convention for the path
/controllers/admin/
and class nameAdmin::
.
Then add admin
column to migration
$ rails g migration add_admin_to_users
1 | add_column :users, :admin, :boolean |
Rails will create a method for all boolean attributes: admin?
###Secure Access for different roles
Next, we can create a AdminController
for all other controllers belongs to Admin.
1 | class AdminController < ApplicationController |
Then other controllers belong to Admin could be like this:
1 | class Admin::TodoController < AdminController |
###CarrierWave upload images to AWS S3
Install gem
1 | gem 'carrierwave' |
Add column to stored migration, for example: videos
$rails migration add_large_cover_to_videos
1 | add_column :videos, :large_cover, :string |
In models/video.rb
1 | mount_uploader :large_cover, LargeCoverUploader |
Create app/uploaders/large_cover_uploader.rb
, and use mini_magick to resize image
1 | class LargeCoverUploader < CarrierWave::Uploader::Base |
Finally, set CarrierWave for AWS S3, in initializers/carrier_wave.rb
1 | CarrierWave.configure do |config| |
Unfortunately, my AWS account has been suspended, so I change the code to store at local
1 | CarrierWave.configure do |config| |
This code also show that if you want to deal with different environment for product
or development
Usually, only upload small size files direct through web page, we can use other AWS S3 client to upload big file.
Another tip here, don’t forget to add new attributes to params.require
, otherwise upload will be failed.
1 | params.require(:video).permit(:title, :description, :category_id, :large_cover, :small_cover, :video_url) |
###RSpec Feature Test
Key Points:
- attach_file
- have_selector
1 | feature 'Admin adds new video' do |