I am looking to securely store the information transmitted from Nuxt.js to Rails

My Desire for Reality

I am hoping to successfully store the data transmitted from Nuxt.js in Rails. Rails is attempting to maintain data association using accepts_nested_attributes_for.

Code

Rails
model/post.rb

class Post < ApplicationRecord
    has_many :post_items, dependent: :destroy
    accepts_nested_attributes_for :post_items, allow_destroy: true

    validates :title, presence: true
    validates :author, presence: true
    validates :image, presence: true
end

model/post_item.rb

class PostItem < ApplicationRecord
 belong_to :post
end

app/controller/posts_controller

class Api::V1::PostsController < ApplicationController
    def index
        posts = Post.all
        render json: posts
    end

    def create
        post = Post.new(post_params)
        if post.save
            render json: 'Succeeded', status: 200
        else
            render json: 'Error', status: 500
        end
    end

        private
         def post_params
            params.require(:post).permit(:title, :author, :image, post_items_attributes: [:content, :status])
         end
end

Nuxt.js

store/todos.js

export const state = () => ({
  list: [],
  hidden: false
})

export const mutations = {
    add (state, text) {
    state.list.push({
      text,
      status: false
    })
  },


  remove (state, todo) {
    state.list.splice(state.list.indexOf(todo), 1)
  },


  edit (state, { todo, text }) {
    state.list.splice(state.list.indexOf(todo), 1, { text })
  },


  toggle (state, todo) {
    todo.status = !todo.status
  },


  cancel (state, todo) {
    todo.status = false
  },

  switching (state) {
    state.hidden = !state.hidden
  }
}

// Rails send
export const actions = {

  postTextAdd ({ commit }, content) {
    const postAxios = this.$axios.$post
    const url = '/api/v1/'

    postAxios(url + 'posts', {
      post: {
        post_items_attributes: {
          content: 'test',
          status: false
        }
      }
    })
      .then((response) => { 
        commit('add', response)
        console.log(response)
      })
  }
}

template

・・・

  methods: {
    addTodo () {
      // postTextAddでRailsに送る
      if (this.selectedTodo.status === false) {
        this.$store.dispatch('todos/postTextAdd', this.itemText)
        this.itemText = ''
        console.log(this.todos)
      } else {
        this.$store.commit('todos/edit', { todo: this.selectedTodo, text: this.itemText })
        this.itemText = ''
        this.$store.commit('todos/toggle', this.selectedTodo)
      }
    },

Error

Terminal

api_1    | Started POST "/api/v1/posts" for 192.168.96.1 at 2021-08-06 07:41:38 +0900
api_1    | Processing by Api::V1::PostsController#create as HTML
api_1    |   Parameters: {"post"=>{"post_items_attributes"=>{"content"=>"test", "status"=>false}}}
api_1    | Completed 500 Internal Server Error in 27ms (ActiveRecord: 0.0ms | Allocations: 4188)
api_1    | 
api_1    | 
api_1    |   
api_1    | TypeError (no implicit conversion of Symbol into Integer):
api_1    |   
api_1    | app/controllers/api/v1/posts_controller.rb:8:in `create'

What I attempted on my own

api_1    | app/controllers/api/v1/posts_controller.rb:8:in `create'

        def create
        post = Post.new(post_params)
        if post.save
            render json: 'Succeeded', status: 200
        else
            render json: 'Error', status: 500
        end
    end

I investigated the above, but I couldn't determine if it was related to the error because create merely saves it.

TypeError (no implicit conversion of Symbol into Integer):
I suspect that the data sent from Nuxt and the data received by Rails are different, however when I referenced the Rails documentation, I found no information other than symbols.

Answer №1

The issue lies within the nested parameters structure. When dealing with nested attributes, they are transferred as an array of hashes rather than a single hash. Therefore, if you modify this:

post: {
        post_items_attributes: {
          content: 'test',
          status: false
        }
      }

to:

post: {
        post_items_attributes: [{
          content: 'test',
          status: false
        }]
      }

Your code should function properly. However, do note that resolving this issue may lead to potential validation errors in your Post model.

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

Tips for making a DIV span the entire width of a page when it is within a column with the Bootstrap class 'col-md-6'

I'm having a little trouble arranging divs next to each other on a page. Specifically, I want to ensure that if there is only one instance of the col-xs-12 col-md-6 div class on the page, it should take up the full width (100%) instead of just 50%. Th ...

Storing personalized HTML content in a database for individual users: A step-by-step guide

I have a JavaScript code snippet similar to this fiddle: http://jsfiddle.net/nj4N4/7/ On my webpage, it displays like this: image. When you click on the "add a year" button, a table resembling year2 appears above the previous year. Now, I'm looking ...

Ensuring that computed value is updated only once in Vue composition API while observing multiple interconnected references

How can we efficiently trigger a costly recalculation only once for a computed value that depends on multiple references, where one reference is dependent on the other? For example: In the following scenario, I aim to compute expensiveData only once. The ...

employ varying XSL stylesheets to display an XML document in a separate window

My issue involves an XML file being transformed by a specific XSL file (XSLT 1.0), which in turn includes multiple other XSL files with various templates. The challenge is to add a button to the rendered XML that, when clicked, opens the same XML in a ...

Locate all instances of words that begin with a certain character and are immediately followed by numbers within

I am searching for words that start with "mc" and are followed by digits only. let myString = "hi mc1001 hello mc1002 mc1003 mc1004 mc mca"; Expected output = [mc1001, mc1002, mc1003, mc1004] This is how I tackled it: const myRegEx = /(?:^|\s)mc(. ...

The Discord Bot is displaying an error message labeled as "DiscordAPIError[50035]"

Here is the code in my ticket_system.js file: const { Client, MessageEmbed, MessageActionRow, MessageButton, Modal, TextInputComponent, } = require("discord.js"); const settings = require("./settings"); ...

HTML- Any suggestions on how to troubleshoot my sticky navbar not functioning properly?

I'm having trouble creating a sticky navbar. I've attempted to use z-index: 999 but it's not behaving as expected. * { margin: 0; padding: 0; } .navbar { display: flex; align-items: center; justify-items: center; position: ...

Can we utilize the elements in Array<keyof T> as keys in T?

Hello, I am trying to develop a function that accepts two parameters: an array of objects "T[]" and an array of fields of type T. However, I am encountering an issue when I reach the line where I invoke el[col] Argument of type 'T[keyof T]' i ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

Avoid triggering child states in ui-router

Here is the progress I have made with ui-router states: $stateProvider .state('tools', { url: '/tools/:tool', template: '<div ui-view=""></div>', abstract: true, onEnter: function ($stateParams, ...

Background image covering entire page is exclusive for the home/index page only

I'm facing an interesting dilemma.. I've built a single-page application with a layout that includes a header, footer, and uses ui-router to display views. Now, my challenge is to have a full-page background on the homepage (index.html) and a wh ...

Issue with translating grid header names in Ag-Grid Vue using i18n without requiring a refresh after changing the language

Localization in my project is done using i18n, but I'm facing an issue where changing the language causes all page translations to display correctly except for the grid header names. The problem resolves itself when I refresh the page. How can I addre ...

Guide on removing the <hr/> tag only from the final list item (li) in an Angular

This is my Angular view <li class= "riskmanagementlink" ng-repeat="link in links"> <h3> {{link.Description}} </h3> <a> {{link.Title}} </a> <hr/> </li> I need assistance with removing the hr tag for the l ...

The impact of React-router's history within the connect function of the react-redux provider

After successfully connecting my presentational-functional component to the redux store using the connect function, I encountered an issue regarding redirection upon triggering the getTask action or when apiGetTask has completed. I attempted to implement t ...

Having trouble formatting the `less` code within a `.vue` file accurately using WebStorm

Pressing option + command + L does not properly format the less code in a .vue file within WebStorm. https://i.sstatic.net/3i6wa.jpg As shown in the image above, the formatting resembles that of css. The block of code within .tag-model-mask should be ind ...

Unleash full rotation capabilities in OrbitControls.js

Currently, I am utilizing OrbitControls.js to rotate the camera around a fixed point. My intention is not to restrict any vertical rotation - my goal is for the camera to smoothly circle the model (orbits around the pivot point). I experimented with remov ...

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

"Trouble with the accordion: How to make the first one open

Is there a way to make the first tab automatically expand when the page is refreshed? I want the General tab to be expanded by default like this: General (top header) (-) lorem ipsum (-) lorem ipsum doller amu site amu doller lorem ipsum (+) lorem i ...

JS: Modifying this function to manage a click on a hyperlink

After following the guide provided here I have successfully implemented a drop down list that sends the value to an external PHP script, retrieves HTML output, and displays it in a "div" on the same page. It works flawlessly. My next objective is to send ...