Tạo một controller trong Ruby on Rails

Lượt xem: 1841

Controller là các lớp của Ruby và các phương thức công khai của chúng là các actions. Và views là template thường được viết hỗn hợp giữa HTML và Ruby.

Để tạo ArticlesController chúng ta chạy controller generator. Chúng ta có thể thêm tỳ chọn --skip-route để loại bỏ việc thêm route


$ docker-compose run --rm app rails generate controller Articles index --skip-routes


Hoặc


$ bin/rails generate controller Articles index --skip-routes

Rails sẽ tạo một số tệp cho bạn:


create  app/controllers/articles_controller.rb
invoke  erb
create    app/views/articles
create    app/views/articles/index.html.erb
invoke  test_unit
create    test/controllers/articles_controller_test.rb
invoke  helper
create    app/helpers/articles_helper.rb
invoke    test_unit

Quan trọng nhất trong số này là việc tạo file controller app/controllers/articles_controller.rb

Nó trông như sau:


class ArticlesController < ApplicationController
  def index
  end
end

Action index đang trống. Khi một action không hiển thị view (chế độ xem) một cách rõ ràng (hoặc nói cách khác là kích hoạt phản hồi HTTP), Rails sẽ tự động render một view khớp với tên của controller và action. Quy ước về cấu hình. Tất cả views sẽ được đặt trong thư mục app/views. Vì vậy, action index sẽ render mặc định app/views/articles/index.html.erb

Hãy mở app/views/articles/index.html.erb và thay thế nội dung của nó bằng:


<h1>Chào mừng bạn đến với khóa học làm quen với ruby on rails cùng dandev</h1>

Nếu trước đó bạn đã dừng máy chủ web để chạy trình tạo bộ điều khiển, hãy khởi động lại nó bằng bin/rails server (Lưu ý mình dùng docker nên sử dụng lệnh docker-compose up -d). Bây giờ hãy truy cập http://localhost:3000/articles và xem văn bản của chúng tôi được hiển thị!

Nếu bạn đã chạy generate mà thêm --skip-route. Thì chúng ta cần phải vào file config/routes.rb để bổ sung route cho article như sau:


Rails.application.routes.draw do
  get "/articles", to: "articles#index"

  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

Xem video thao tác cùng dandev nhé