Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Rails form with a Vue component

I'm wondering what the best way to create a Rails form using a Vue SFC (single file component) would be.

When one uses the form_for method, some hidden input fields are generated by Rails, such as the authenticity token and the submission method, in the event we are submitting via PUT or PATCH instead of POST. However, if I extract the form into a Vue template, I lose all that nice functionality.

How would one define a Vue SFC but not lose all the good Rails functionality we are given in a Rails template (hidden field for PUT/PATCH and for the authenticity token)?

Thanks in advance!

like image 293
DaniG2k Avatar asked Oct 16 '25 11:10

DaniG2k


1 Answers

After extensive research I hope to be able to answer this question.

For forms creating in a .vue file you need Axios and to configure it in the Vue app. My reference is here

Specifically

import TurbolinksAdapter from 'vue-turbolinks';

document.addEventListener('turbolinks:load', () => {
  // This code will setup headers of X-CSRF-Token that it grabs from rails generated token in meta tag.
  axios.defaults.headers.common['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')

  new Vue({
    ...
    mixin: [TurbolinksAdapter],
    ...
  })
})

Essentially, if you're like me, you use Rails more as an API service, and Vue will be the front-end app running for the user. I want to keep Ruby out of the front end as much as I can. This comes from it doesn't seem like there is a way for ERB to be used with Vue. I've tried adding the extension .vue.erb but the ERB is parsed literally. So then Vue will make requests to my Rails back-end via axios which will now have the CSRF token for Rails authenticity. Rails will return the JSON from the request and Vue will handle appropriately.

I'm using Rails 6. The entire process would be

  1. Set up project with Rails and Vue
  2. Install axios and vue-axios in package.yml
  3. Set up axios defaults with the X-CSRF-Token header using the code above.

The link I attached also goes into more detail. Again this is for anyone who wants to use Rails as a back-end and Vue as a front-end and keep them separated as much as possible.

like image 102
Marcus Salinas Avatar answered Oct 19 '25 00:10

Marcus Salinas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!