Là một newbie trong lập trình nói chung là lập trình web nói riêng thì việc cài đặt, config môi trường sao cho chương trình chạy được là việc chiếm khá nhiều thời gian của bản thân trong quá trình học.
Ở bài viết này sẽ nói về cách tích hợp, cài đặt môi trường để kết hợp VueJS và Ruby on Rails vào cùng 1 dự án.
1. Khái quát
Một cách khá đơn giản để tích hợp VueJS và Ruby on Rails là chúng ta sẽ chỉ sử dụng Rails như 1 server API dùng để lưu trữ data. Còn ta sẽ dùng client server của VueJS để fetch, thao tác và hiển thị dữ liệu.
2. Khắc phục CORS error
- 
CORS là gì ?
CORS là viết tắt củaCross-Origin-Resource.
Các code mà chạy trên các domains, protocols hoặc ports khác nhau thì các request giữa chúng nó được gọi làcross-origin.
Các browser web hiện đại hiện nay hầu hết đều mặc định chặn các requestcross-origintừ đầu.
=> Nếu bạn làm việc trên app mà Frontend Server và Backend Server là 2 server riêng biệt thì lúc này chúng ta cần config CORS để cho chúng có thể trao đổi thông tin với nhau. Ở đây cần config CORS sao cho server của vueJS và server của Rails hoạt động được với nhau. - 
Bỏ comment
gem 'rack-corstrong Gemfile
Sau đấy thì chạybundle install - 
Update lên rails 7
Ngày viết bài này là ngày 14/7/2022. Không hiểu vì lý do gì mà CORS nó không chạy trên rails 6. Update lên rails 7 thì CORS nó lại chạy bình thường.
Sửa lại gem rails trong Gemfile thànhgem 'rails', '~> 7.0', '>= 7.0.3.1'.
Chạybundle install.
Chạyrails app:update.rails db:migrate RAILS_ENV=development - 
config/initializes/cors.rb
 
Rails.application.config.middleware.insert_before 0,Rack::Corsdo
  allow do
    origins "http://localhost:8080/"# URL này là URL của client server, ở đây port mặc định của vueJS là port 8080
    resource "*",
      headers::any,
      methods:[:get,:post,:put,:patch,:delete,:options,:head]endend
3. Tạo db
- Tạo rails app only API. 
rails new vue-rails --api cd vue-railsrails g scaffold post content:textrails db:migrate- Tạo mới folder và file 
app/controllers/api/v1/posts_controller.rb 
classApi::V1::PostsController<ApplicationController
  before_action :set_post, only:[:show,:update,:destroy]# GET /postsdefindex@posts=Post.all
    render json:@postsend# GET /posts/1defshow
    render json:@postend# POST /postsdefcreate@post=Post.new(post_params)if@post.save
      render json:@post, status::created, location:@postelse
      render json:@post.errors, status::unprocessable_entityendend# PATCH/PUT /posts/1defupdateif@post.update(post_params)
      render json:@postelse
      render json:@post.errors, status::unprocessable_entityendend# DELETE /posts/1defdestroy@post.destroy
  endprivate# Use callbacks to share common setup or constraints between actions.defset_post@post=Post.find(params[:id])end# Only allow a list of trusted parameters through.defpost_params
      params.require(:post).permit(:content)endend
- Tạo db bằng rails c
Post.create!(content: "1st post")Post.create!(content: "2nd post")
Sau khi tạo db xong chúng ta có thể xem db dưới dạng json tronghttp://localhost:3000/api/v1/posts![image.png]()
 
4. Tạo project vue
cd vue-rails- install vue CLI 
yarn global add @vue/cli vue create frontend- Add vue router 
vue add router. Vue router thích thì add không thì cũng không sao. - Sửa lại file 
app/frontend/src/main.js 
import{ createApp }from'vue'import App from'./App.vue'import router from'./router'createApp(App).use(router).use(router).mount('#app')
5. Fetch API và hiển thị dữ liệu
- frontend/src/views/Home.vue
 
<template><divclass="home"><tableclass="table table-hover"><thead><tr><thscope="col">id</th><thscope="col">Content</th></tr></thead><tbody><trv-for="item in items":key="item.id"><thscope="row">{{ item.id }}</th><td>{{item.content}}</td></tr></tbody></table></div></template><script>import{ref, reactive}from'vue'exportdefault{setup(){var items =ref(null);const fetchURL ='http://localhost:3000/api/v1/posts';fetch(fetchURL).then(response=> response.json()).then(data=>{
        items.value = data
        console.log(data)}).catch(error=> console.error(error));return{items}},}</script>
- 
Mở console ta sẽ thấy thông tin data sau khi fetch thành công được in ra.
![image.png]()
 - 
Run
yarn servevà truy cập vàohttp://localhost:8080/ta sẽ thấy db sẽ được hiển thị ra màn hình.![image.png]()
 
Tổng kết
Vậy chúng ta đã fetch API và hiển thị dữ liệu nhận về ra ngoài màn hình thành công 😊😊.
Mặc dù app này chỉ có mỗi chức năng hiển thị, nhưng chúng ta cũng có thể làm thêm các chức năng create, update, delete bằng cách tương tự.
Nguồn: viblo.asia



