When POSTing using axios and devise_token_auth with Nuxt.js and Ruby on Rails, I got stuck in a simple way, so I will summarize it with a memorandum.
The settings of devise_token_auth are omitted.
The following URL was helpful, so it may be good to see it.
https://github.com/lynndylanhurley/devise_token_auth https://qiita.com/Masahiro_T/items/6bc49a625b437a7c2f45 https://sainu.hatenablog.jp/entry/2018/08/11/194319
Since we have introduced FormObject, we will include that as well.
articles_controller.rb
class ArticlesController < ApplicationController
def create
@article = ArticleForm.new(article_params).save
if @article
#abridgement
end
end
private
def article_params
json_request = ActionController::Parameters.new(JSON.parse(request.body.read))
json_request.permit(
:title,
:description,
).merge(user_id: current_user.id)
end
end
articles_form.rb
class ArticleForm
include ActiveModel::Model
attr_reader :title, :description
validates :title, presence: true, length: { maximum: 50 }
validates :description, length: { maximum: 300 }
def initialize(article_params)
@article = article_params
end
def save
return false if valid?
Article.create(@article)
true
end
end
Now you are ready to POST.
Since I was supposed to mess with Json when POSTed, I had to write a process to parse Json. (I was really into it here.)
def article_params
json_request = ActionController::Parameters.new(JSON.parse(request.body.read))
json_request.permit(
:title,
:description,
).merge(user_id: current_user.id)
end
I've saved it in the following article (or rather, copy the Parse part of Json), so I'll post it.
http://tabunmuri.hatenablog.com/entry/2015/07/02/rails%E3%81%A7json%E3%81%AB%E3%80%81permit%E3%81%A7%E8%A6%81%E7%B4%A0%E3%83%81%E3%82%A7%E3%83%83%E3%82%AF%E3%81%97%E3%81%9F%E3%81%84%E6%99%82%E3%81%AE%E6%96%B9%E6%B3%95
I will omit the implementation written in Component and cut out only the implementation of the POSTed part with axios that is done in Vuex.
article.js
export const actions = {
async postArticle({ dispatch }, article) {
await this.$axios
.post('/articles', article, {
headers: {
'Content-Type': 'multipart/form-data', //For the assumption of sending thumbnail images
'access-token': this.state.user.userToken.accessToken,
client: this.state.user.userToken.client,
uid: this.state.user.userToken.uid,
},
})
.then(() => dispatch('getArticleList'))
.catch((error) => console.log(error))
},
}
I packed the token of devise_token_auth in a cookie and wrote it to Vuex at the time of nuxtServerInit, so that the Token can be inserted in the header at the time of request.
By the way, although it is not Ruby on Rails, it has a similar implementation when using GO echo, and the memorandum is summarized below.
https://qiita.com/arthur_foreign/items/fadd784610d764419786
Recommended Posts