0

I have a Rails app with nested form attributes and I'm using Vue.js. My first level nesting is working fine for creating and editing, but for deeper nested attributes, how can I rectify the issue of Rails needing "_attributes" appended to the associated attributes to process the update?

How can I access the deeper nested attributes (in my case, the "minimum_premia") and pass them to the Vue instance with the "_attributes" suffix so the submit goes through?

//_form.html.erb

<%= content_tag :div,
data: {
  id: product.id,
  product: product.to_json(except: [:id, :created_at, :updated_at]),
  coverages_attributes: product.coverages.to_json(:except => 
  [:product_id, :created_at, :updated_at], :include => [:minimum_premia 
  => {:except => [:coverage_id, :created_at, :updated_at]}])
} do %>

...

<div v-for="(minimum_premium, index) in coverage.minimum_premia_attributes">
  <label>Amount</label>
    <input type="number" v-model="minimum_premium.amount">
</div>


//vue.js

var id = element.dataset.id
var product = JSON.parse(element.dataset.product)
    var coverages_attributes = JSON.parse(element.dataset.coveragesAttributes)
    coverages_attributes.forEach(function(coverage) {coverage._destroy = null})
    product.coverages_attributes = coverages_attributes

var app = new Vue({
  el: element,
  data: function() {
      return { id: id, product: product }
  },
  methods: {
    addCoverage: function() {
      this.product.coverages_attributes.push({
        id: null,
        name: "", 
        _destroy: null,
        minimum_premia_attributes: [{
          id: null,
          amount: null
        }]
      })
    } 
1

1 Answer 1

0

This was solved using Jbuilder to generate a JSON object using the necessary appended names.

For example:

json.product do
  json.coverages_attributes product.coverages do |coverage|
    json.minimum_premium_rules_attributes coverage.minimum_premium_rules do |minimum_premium_rule|
      json.(minimum_premium_rule, :minimum_premium)
    end
  end
end

The coverage.minimum_premium_rules retrieved from the database were passed into vue using the proper nested attribute naming - minimum_premium_rules_attributes -that Rails needs to update the record.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.