Troubleshooting Database Saving Problem with Vue.js and Ruby on Rails

Trying to configure a nested form with Vue.js in a Rails application to save ingredients for a recipe. While all other details of the ingredients are saving correctly, the ingredient name (from an input field) is not getting saved in the database. How can I ensure that the name field gets saved?

app/models/ingredient.rb

class Ingredient < ApplicationRecord
  belongs_to :recipe
end

app/models/recipe.rb

class Recipe < ApplicationRecord
  has_many :ingredients
end

app/views/index.html.erb

<h1>Index</h1>
<!-- Rest of the code remains the same -->
...

app/views/api/v1/recipes/index.json.jbuilder

json.array! @recipes, partial: "recipe", as: :recipe

app/views/api/v1/recipes/_recipe.json.jbuilder

 <!-- JSON output template remains the same -->
...

app/controllers/api/v1/recipes_controller.rb

 <!-- Controller logic for handling recipes remains the same --> 
...

app/javascripts/recipes_ctrl.js

$(document).on('ready', function() {
  new Vue({
    el: '#app',
    data: {
      // Data structure for Vue instance remains the same
      ...
    },
    methods: {
      // Methods for handling newRecipe, newIngredient, and removeIngredient remain the same
      ...
    }
  })
})

This terminal output shows my efforts so far, with the CSRF token issue being handled:

Processing by Api::V1::RecipesController#create as JSON
  Parameters: {"name"=>"", "chef"=>"", "cooktime"=>"", "amount"=>"", "description"=>"", "favorite"=>false, "ingredients"=>[{"name"=>"test"}, {"recipe_id"=>""], "recipe"=>{"name"=>"", "chef"=>"", "cooktime"=>"", "amount"=>"", "description"=>"", "favorite"=>false}}
Can't verify CSRF token authenticity.
   (4.3ms)  BEGIN
  SQL (5.5ms)  INSERT INTO "recipes" ("name", "chef", "cooktime", "description", "favorite", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["name", ""], ["chef", ""], ["cooktime", ""], ["description", ""], ["favorite", false], ["created_at", 2017-02-05 17:29:34 UTC], ["updated_at", 2017-02-05 17:29:34 UTC]]
  SQL (51.5ms)  INSERT INTO "ingredients" ("recipe_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["recipe_id", 18], ["created_at", 2017-02-05 17:29:34 UTC], ["updated_at", 2017-02-05 17:29:34 UTC]]
   (3.1ms)  COMMIT
  Rendering api/v1/recipes/show.json.jbuilder
  Ingredient Load (0.7ms)  SELECT "ingredients".* FROM "ingredients" WHERE "ingredients"."recipe_id" = $1  [["recipe_id", 18]]
  Rendered api/v1/recipes/_recipe.json.jbuilder (12.2ms)

Answer №1

In my opinion, there is no need for @recipe.ingredients.build in the create action. To save in a different way, you should include

accepts_nested_attributes_for :ingredients
in the Recipe 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

applying multiple conditions to filter data in javascript

I have been working on filtering data based on input, and it is functioning well. However, I am looking to add an additional condition to the filter. I want it to return if either the title or another value (such as sendFrom) is provided. const newData = ...

Utilizing backbone.js for XML parsing and converting to JSON

I am new to utilizing Backbone.js and need assistance with converting an XML file into a JSON format. The XML file structure is similar to the example below, where 'Measurement' is in a list type and parsing is required. <Counter name=""> ...

Ajax Syntax Error: Unexpected Token U

I have been struggling all day with an issue while trying to send json data via ajax to Express. Here is how my ajax code looks like: $('#saveClause').click(function () { var username = document.getElementById('postUserName').inne ...

Attempting to retrieve key-value pairs from a nested JSON array

I am attempting to extract values along with their corresponding key names from a nested JSON array resData =[ { _index: 'web', _type: 'event', _id: 'web+0+93', _score: null, _source: { 'os-nam ...

Convert items to an array utilizing lodash

I need assistance converting an object into an array format. Here is the input object: { "index": { "0": 40, "1": 242 }, "TID": { "0": "11", "1": "22" }, "DepartureCity": { "0": "MCI", "1": "CVG" }, "ArrivalCity": { ...

Implementing jQuery and JavaScript validation for email addresses and usernames

Are the online validations being used incorrectly or is there a serious issue with them? I came across an example of a site using jQuery validation, but when I entered "44" for a name and ##@yahoo.com for an email address, no warning appeared. I haven&apo ...

When running a callback function, the "this" of an Angular 2 component becomes undefined

One issue I'm facing is with a component that fetches data from a RESTful endpoint using a service, which requires a callback function to be executed after fetching the data. The problem arises when attempting to use the callback function to append t ...

Tips for viewing the content of an authentication-required API in a browser

Currently, I am in the process of developing an Android project that requires accessing a specific github API. This particular API contains vital information regarding user repositories. Before diving into Android programming, I am eager to explore the c ...

The utilization of 'new' is not allowed with an expression that does not have a call or construct signature in TypeScript

While searching for a solution, I stumbled upon this link which unfortunately did not provide the answer I was looking for: Cannot use 'new' with an expression whose type lacks a call or construct signature I am facing a similar issue. In my JavaS ...

The loop feature in Swiper.js seems to be malfunctioning and not functioning as

I'm currently in the process of setting up a carousel using swiper.js and here is my setup: { slidesPerView: 1, slidesPerColumn: 1, initialSlide: this.initialSlide, loop: true } As expected, I'm encountering an issue where dupl ...

The NodeJS nedb function seems to be ignoring the await keyword

The time it takes for the function checkExists to run is too lengthy. Despite attempting to implement await and async functions, using var exists = await checkExists(data.email); still results in undefined value due to not properly awaiting for checkExists ...

Generating Dynamic Image Sources with Vue 3 using Rollup

Dealing with dynamic image src using Rollup in a Vite-app: <img :src="??" alt=""> Any suggestions on how to achieve this without Webpack's require? ...

Vue - Retrieve the id of the specific post that was clicked

My main objective is to track the number of clicks for each post. So far, I have only been able to retrieve the number of clicks per post in the console: https://i.sstatic.net/YyIdw.png However, I need to identify which post was clicked. To distinguish ...

Preventing recursive setTimeout() clearing in VueJS Route Component when changing routes

I have developed a messaging platform with real-time updates using VueJS for the front-end and PHP for the back-end. The process involves using setTimeout() to fetch new messages from the server as shown below: var Conversation = Vue.component(&a ...

Achieve instant redirection upon user logout with Angular and Meteor

Within a Meteor application utilizing Angular, there exists a specific state that mandates the user to be logged in. Currently, this requirement is implemented using $meteor.requireUser() function run($rootScope, $state) { $rootScope.$on('$state ...

What is causing the continuous appearance of null in the console log?

As part of my JavaScript code, I am creating an input element that will be inserted into a div with the id "scripts" in the HTML. Initially, I add a value to this input field using JavaScript, and later I try to retrieve this value in another JavaScript fu ...

How to update newly added information through the existing form in ReactJS

Currently, I am working on a CRUD operation in my project. So far, I have successfully implemented the functionalities to add, delete, and display data. However, I am facing challenges with updating existing data. Despite trying various methods, none of th ...

Tips for preserving HTML tags in responses within React Native applications

How can I preserve HTML tags in the response when using React Native? Here is an example of a response from Postman: { "enable": true, "faq": [ { "answer": "<ol>some text</ol>" ...

How can I create an input field that comes with a preset value but can be updated by the user with a different name?

I am in need of a solution that will enable a user to update text on a webpage dynamically. I have been unable to find any information on how to achieve this. Is there anyone aware of a method to implement this feature? Perhaps a library or utilizing Vue ...

KendokendoNumericTextBox Unable to assign a value

After upgrading to the latest version of Kendo 2020, everything seems to be working smoothly except for the kendonumerictextbox control. I encountered an error when attempting to set a value to the kendonumerictextbox. $('#Taxes').data("kendoNu ...