Bước 2: Tạo mới dự án Rails
Mở terminal và chạy lệnh sau để tạo mới dự án Rails:
code
rails new tenn-du-an --database=postgresql
Ghi chú: ten-du-an là tên dự án của bạn. Trong ví dụ này, chúng ta sử dụng PostgreSQL làm cơ sở dữ liệu. Bạn có thể thay thế bằng cơ sở dữ liệu khác như MySQL.
Bước 3: Chỉnh sửa Gemfile
Mở file Gemfile và thêm hotwire-rails vào nhóm :development và :test:
code
group :development, :test do
gem 'hotwire-rails'
end
Lưu lại và chạy lệnh bundle install để cài đặt gem mới.
Bước 4: Tạo controller, view và model
Để tạo controller, view và model cho dự án, chạy các lệnh sau:
code
rails g controller Posts
rails g model Post title:string content:text
rails db:migrate
Bước này sẽ tạo ra một controller có tên là PostsController và một model có tên là Post với hai trường title và content. Lệnh rails db:migrate sẽ chạy migration để tạo bảng trong cơ sở dữ liệu.
Bước 5: Tạo routes
Mở file config/routes.rb và thêm các routes cho CRUD operations:
code
Rails.application.routes.draw do
resources :posts
root 'posts#index'
end
Lưu lại và tiến hành tạo routes bằng lệnh rails routes để xác nhận.
Bước 6: Tạo view và partial
Tạo file app/views/posts/index.html.erb với nội dung sau:
Trong thư mục app/services, tạo một file create_post_service.rb với nội dung sau:
ruby
class CreatePostService
def initialize(params)
@params = params
end
def call
Post.create(@params)
end
end
Tạo một file update_post_service.rb với nội dung sau:
ruby
class UpdatePostService
def initialize(post, params)
@post = post
@params = params
end
def call
@post.update(@params)
end
end
Và cuối cùng, tạo một file destroy_post_service.rb với nội dung sau:
ruby
class DestroyPostService
def initialize(post)
@post = post
end
def call
@post.destroy
end
end
Đây là một ví dụ cơ bản về việc tạo một dự án Rails với tích hợp Hotwire và triển khai một ví dụ CURD. Bạn có thể tùy chỉnh và mở rộng dự án theo nhu cầu của mình.