---
# System prepended metadata

title: 20221122 Rails
tags: [Ruby & Rails]

---

# 20221122 Rails
###### tags: `Ruby & Rails`
<政庭>
### 幫網頁添加元件 font awesome
```javascript
yarn add @fortawesome/fontawesome-svg-core
```
在`favorite_btn_controller.js`檔案新增
```javascript
import { library, dom } from '@fortawesome/fontawesome-svg-core'
import { faThumbsUp as thumbsUpSolid} from '@fortawesome/free-solid-svg-icons'
import { faThumbsUp as thumbsUpRegular} from '@fortawesome/free-regular-svg-icons'
```
```javascript
initialize() {
    this.btnState = false;
    library.add(thumbsUpSolid, thumbsUpRegular)
  }

  connect() {
    dom.watch();
  }
```
### 新開一個路徑api/wish_lists/id/like
在`routes.rb` 檔案新增一個
```ruby
namespace :api do
      resources :wish_lists, only:[] do
        member do
          patch :like
        end
      end
  end
```
在`favorite_btn_controller.js`的`toggle funciton`底下新增
```javascript
fetch("/wish_lists/2/like", {method: "patch"}).then((resp)=>{
      console.log(resp);
    }).catch((err)=>{
      console.log(err);
    })
    this.btnState = !this.btnState;
  }
```



---
<侑庭>
font awesome

```ruby!
  # /api/wish_lists/2/luke
  namespace :api do 
    resources :wish_lists, only: [] do
      member do 
        patch :link
      end
    end
  end
```




```javascript!
fetch('/wish_lists/100/like',{method: 'patch'})
    .then((resp)=>{
      console.log(resp);
    })
    .catch((err)=> {
      console.log(err);
    })
```

![](https://i.imgur.com/uhyroG4.png)



在

---
<于婷>

## 添加icon
下載套件[fontawesome](https://fontawesome.com/docs/apis/javascript/get-started)
```
$ yarn add @fortawesome/fontawesome-svg-core
$ yarn add @fortawesome/free-solid-svg-icons
```

## 多對多 關聯

```
$ rails g model LikeWishList user:belongs_to wish_list:belongs_to
```
```ruby=
  has_many :like_wish_lists
  has_many :liked_wish_lists, through: :like_wish_lists, source: :wish_list
```

```ruby=
  has_many :like_wish_lists
  has_many :liked_users, through: :like_wish_lists, source: :user
```



![](https://railsbook.tw/images/chapter18/many-to-many-tables.png)
![](https://railsbook.tw/images/chapter18/many-to-many-model.png)


圖片取自[為你自己學Ruby](https://railsbook.tw/chapters/18-model-relationship)

