Utilizing Rails with Vue.js for intricate nested attribute structures

After following a tutorial on gorails to create a nested form, I successfully implemented it. However, my challenge arose when trying to nest a model within another nested model. Initially, I have a main model called Survey, and then I introduced the Question model using vue.js for form creation. Next, I added the Choice model under the question in the survey controller params. My first hurdle is figuring out how to define/implement this in the hello_vue.js file. And secondly, I need to understand how to create form elements in new.html.

This snippet shows my survey.rb model:

class Survey < ApplicationRecord
    has_many :questions, dependent: :destroy
    accepts_nested_attributes_for :questions, allow_destroy: true
    belongs_to :user
end

and surveys_controller.rb:

class SurveysController < ApplicationController
  before_action :set_survey, only: [:show, :edit, :update, :destroy]

    def survey_params
      params.require(:survey).permit(:user_id, :name, questions_attributes:[:id,:survey_id, :title, :qtype, :_destroy, choices_attributes:[:id,:question, :ctext]])
    end
end

This section showcases the nested model of Survey - question.rb:

class Question < ApplicationRecord
    enum qtype: [:multiple_choice, :check_boxes, :short_answer]
    belongs_to :survey
    has_many :choices
    accepts_nested_attributes_for :choices, allow_destroy: true
end

Finally, here is the vue.js file snippet:

 (Code Snippet)

_form.html.erb

<%= content_tag :div,
    id: "survey-form",
    data: {
      survey: survey.to_json(except: [:created_at, :updated_at]),
      questions_attributes: survey.questions.to_json,

    } do %>

(Additional Code)

    <% end %>

Answer №1

After following the same tutorial, I encountered issues using JSON.parse with more intricate nested attributes. A helpful solution is utilizing Jbuilder to construct your JSON objects and exploring the gon gem for passing Rails variables into Javascript. This approach simplifies querying your database and transferring results into your Javascript file through the nested naming structure required by Rails. For instance...

survey = @survey

json.id survey.id

json.survey do
  json.(survey, :user_id, :name)  
  json.questions_attributes survey.questions do |question|
    json.(question, :id, :title, :qtype, :_destroy)
    json.choices_attributes question.choices do |choice|
      json.(choice, :id, :ctext)
    end
  end

This method enables you to perform tasks like...

var survey = gon.survey

Rather than...

var survey = JSON.parse(element.dataset.survey)

You can send gon.jbuilder from your controller action and have your specified JSON object easily accessible in Vue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Insert stand-alone text into text field for Sudoku viewing

I am currently working on creating a Killer Sudoku grid with jigsaw bold lines inside regular 3x3 squares. Each cell needs to display a number and an operation at the top right. I have set up a table with each cell as a textbox. However, I'm strugglin ...

Utilizing the JavaScript Array.find() method to ensure accurate arithmetic calculations within an array of objects

I have a simple commission calculation method that I need help with. I am trying to use the Array.find method to return the calculated result from the percents array. The issue arises when I input a price of 30, as it calculates based on the previous objec ...

Static folder images not appearing in Nuxt 3

I am currently using Nuxt 3 and here is the directory structure I am working with https://i.sstatic.net/k09i3.png This is how images are being loaded <img src="/images/index/pic-left.svg" /> I also attempted to remove the / at the begin ...

Encountered Axios GET error, [nodemon] server crashed - currently monitoring for any file modifications before relaunching (using express js, mysql, and react

Initially, my backend was running smoothly until I encountered an issue with axios not being able to retrieve GET data from the backend. In an attempt to resolve this, I changed the port to 8000 in the index.js file, but this caused the backend server to c ...

Issue: Node Sass 8.0.0 is not compatible with the version ^4.0.0

I encountered an error when starting a React app with npm start. How can I resolve this issue? ./src/App.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/resolve-url-loader??ref--6-oneO ...

Update the image source when hovering over the parent element

Check out this snippet of HTML code: <div class="custom text-center threeBox ofsted"> <a class="ofsted" title="ofsted report" href="http://reports.ofsted.gov.uk/"> <img class="text-center ofstedLogo" src="images/ofsted_good_transparen ...

Collect various user inputs

I'm having an issue with getting multiple user inputs in my program. I have a function that takes user input based on code from the node.js documentation, but it only allows me to receive one input at a time. How can I modify the code so that I can ge ...

Link scripts can sometimes cause issues with node.js

Greetings! I have successfully created a client-side SPA using vanilla-router. However, my Node.js server sometimes encounters an error when attempting to load a linked script. Uncaught SyntaxError: Unexpected token '<' This error only oc ...

Can you guide me on implementing first-person controls in react-three-fiber?

I'm attempting to set up a scenario where the camera remains stationary while allowing users to rotate the view around either the y or x axis by dragging their mouse. I'm looking for something akin to the functionality seen on threejs.org/example ...

Creating views solely with HTML, JavaScript, and AJAX, without the need for JSP or any similar technologies

I've been exploring the idea of creating an MVC architecture using only javascript, html, and AJAX (potentially jQuery or a similar library) to generate views, instead of relying on JSP, Velocity, or Freemarker in Java applications. This concept could ...

Setting up a new directory with specific permissions using Node.js

I am facing an issue while using the mkdirp node module to create a folder. It is being created with permissions set at 0775 instead of the required 0777. The official documentation states that it should default to 0777, but in my case, it is showing up ...

Establish a WebSocket connection via Meteor.js

How do we establish a Websockets connection in Meteor? Can we achieve this using the following code: ws = new WebSocket('ws://localhost/path'); ws.on('open', function() { ws.send('something'); }); ws.on('message&apo ...

The .val() function in jQuery can sometimes give different results when used on input elements with placeholder text in Firefox compared to Chrome

After analyzing the given HTML code, I've noticed discrepancies in the values returned by jQuery in Firefox and Chrome: HTML: <input type="text" name="name" id="name" placeholder="Type Here"> <input type="email" name="email" id="email" plac ...

Retrieve the output of a JavaScript onclick event

Does anyone know how to scrape the URL generated by a JavaScript onclick function on a website without opening new tabs or windows? I think Selenium might work, but I'm not sure how to code it. Here is the onclick JS function: 'tr class="linha ...

Combining Laravel with React

Currently in the process of developing a substantial real estate listings platform with react and laravel. Can you suggest which approach would be better for this project and explain why? Option 1: Implement laravel react presets and store all react compo ...

Using jQuery to create delays with stop functionality

Take a look at this navigation layout main navigation section secondary navigation section sub-navigation (only visible on hover of main or secondary nav) I need to create a delay in the fadeOut function so that users have enough time to move their mou ...

Encountering an issue while attempting to implement Redux Toolkit alongside the MUI ToggleButtonGroup component

The error message initially started as: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. When I attempted to update the Redux state using a dispatcher, the handleChange function suddenly showed an e ...

Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this. Below is an example of my controller: public function index(Request $request) { ...

Updating an array object property in state using Redux

I have a function that deals with action types and state updates. I decided to switch from using the "slice" method to the concat method for updating the state. The original code had a slice solution to update the object, but it didn't work as expecte ...

Ways to monitor automatic data alterations within a Vue JS component

I have a method that updates data within the component itself, for example: Vue.component('component', { template: '#component', data: function () { return { dataToBeWatched: '' } }, methods: { chang ...