Home > ruby on rails > Rails: nested models disappearing after validation

Rails: nested models disappearing after validation

January 26Hits:1
Advertisement

I have a model:

class Invoice < ActiveRecord::Base   belongs_to :case   has_many :invoice_positions    accepts_nested_attributes_for :invoice_positions, allow_destroy: true 

And i have a form createn with https://github.com/nathanvda/cocoon but i have one small problem - after validation fails all invoice_positions disappears.

Here is part of form where i render positions:

<% f.fields_for :invoice_positions do |invoice_position| %>             <%= render 'invoice_position_fields', f: invoice_position %>         <% end %>  

And my create action in controller:

def create     @case = Case.find(params[:case_id])     @invoice = Invoice.new(invoice_params)     @invoice.case = @case      if @invoice.save       flash[:success] = 'Faktura zapisana'       redirect_to case_case_invoices_path(@case)     else       @invoice.invoice_positions.build(params[:invoice_positions_attributes])       render 'new'     end   end 

Here are parameters from console:

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"f1IUw+mt10QX3PFy4g1Hv+8VkD8sQR7roPKrh+6N4Va6Un2mGrR86/XR91hsRjI4V6FLNyavyc8TeGZt9E2RoQ==", "invoice"=>{"date(1i)"=>"2016", "date(2i)"=>"1", "date(3i)"=>"26", "pay_date(1i)"=>"2016", "pay_date(2i)"=>"2", "pay_date(3i)"=>"5", "city"=>"Rzeszów", "person"=>"Test Test", "comment"=>"", "invoice_positions_attributes"=>{"1453833757786"=>{"name"=>"dwqdwqdwq", "kind"=>"", "price"=>"", "quantity"=>"", "tax"=>"", "_destroy"=>"false"}, "1453833759600"=>{"name"=>"wdqdwqqwd", "kind"=>"", "price"=>"", "quantity"=>"", "tax"=>"", "_destroy"=>"false"}}}, "case_id"=>"1"} 

And here the invoice_position_fields view:

<tr class="nested-fields">   <td>     <%= f.text_field :name, class: 'form-control', placeholder: 'Nazwa' %>   </td>   <td>     <%= f.text_field :kind, class: 'form-control', placeholder: 'Typ (np. usł., szt.)' %>   </td>   <td>     <%= f.text_field :price, class: 'form-control', placeholder: 'Cena jedn. netto' %>   </td>   <td>     <%= f.text_field :quantity, class: 'form-control', placeholder: 'Ilość' %>   </td>   <td>     <%= f.text_field :tax, class: 'form-control', placeholder: 'VAT' %>   </td>   <td></td>   <td>     <%= link_to_remove_association icon('trash'), f, {class: 'btn btn-danger'} %>   </td> </tr> 

Answers

<%= f.fields_for :invoice_positions do |invoice_position| %>

instead of

<% f.fields_for :invoice_positions do |invoice_position| %>

2.5h to get it....

--

Rich Peck Edit

You can clean up your create action a little:

def create
   @case    = Case.find params[:case_id]
   @invoice = @case.invoices.new invoice_params

Related Articles

  • Rails: nested models disappearing after validationJanuary 26

    I have a model: class Invoice < ActiveRecord::Base belongs_to :case has_many :invoice_positions accepts_nested_attributes_for :invoice_positions, allow_destroy: true And i have a form createn with https://github.com/nathanvda/cocoon but i have one sm

  • Rails nested models and virtual attribute initializationJanuary 27

    I have a problem understanding how are attributes "sent" to nested model(s), and if is possible to do this for model with virtual attrubute too. I have three models: class User < ActiveRecord::Base ... has_and_belongs_to_many :clearancegoods

  • Rails - Why does my nested model form not require 'accepts_nested_attributes_for'February 9

    I have two models item and user_item. Item has many user_items and user_items belongs to item. I have a form where a user can create a new item. In the form a user should include a picture. The name, description, and tags get saved to a new item obje

  • Problem validating parent model with nested models in modelbuilder

    Problem validating parent model with nested models in modelbuilderMarch 24

    I have a parent model with several nested models. I'm having trouble getting the parent model to validate. The issue is with sub model 4. The two screenshots are of the parent model and sub model 4. The output from sub model 3 feeds into parameter "M

  • Rails routes for self nested modelsJanuary 15

    In my rails app I have a Task model. In my app, my tasks can have substasks and so on. Since my subtasks are tasks with only a parent task, I did a self-nested model such as class Task < ActiveRecord::Base ## Self Join has_many :subtasks, class_name:

  • rails with most nested models and cocoon gem;

    rails with most nested models and cocoon gem;February 16

    I have a rails4 app with nested model form. There is a product model that has_many product_features, has_many product_usecases and has_many product_competitors. Everything works fine except when I load the page only the first nested model (product_fe

  • Before validation on nested modelJanuary 9

    I have a nested model items and I am trying to multiply two columns together cost and quantity to set the last column price. I need to set the column price before the form is saved and i need to also validate the model. The before_validation call bac

  • Building Your First Rails Application: Models

    Building Your First Rails Application: ModelsMarch 14

    If you've heard about Rails but are yet to take the plunge, there has never been a better time to dive in. Rails 3, the most recent major release, not only marks a major landmark in maturity for the framework itself, but is also a sign of a mature co

  • rails: nested-form doesn't render in viewJanuary 25

    I have models like this post.rb has_many :items accepts_nested_attributes_for :items item.rb has_one :heading, dependent: :destroy has_one :content, dependent: :destroy has_one :link, dependent: :destroy has_one :movie, dependent: :destroy has_one :p

  • Request processing failed; nested exception is javax.validation.ConstraintViolationExceptionJanuary 26

    i am having an issue with Hibernate validators when i click on submit button for saving one of my component which have few validations annotations for component, i am geeting HTTP Status 500 error. Here is my spring controller code. @RequestMapping(v

  • Nested Iteration with model builder - using nested models

    Nested Iteration with model builder - using nested modelsSeptember 7

    I'm new to using model builder and have to do a nested iteration (for every month I have to iterate through 6 parameters). I am thinking of doing that by using nested models. One model doing the interation through monthes and then providing the curre

  • PHP MVC class with controller and nested model

    PHP MVC class with controller and nested modelNovember 26

    I had asked a first question about this class a while ago and got a few answers here which made me rewrite it completely. I removed all statics and globals, added my variables as arguments for the constructor, and pass them again as reference through

  • Using global parameters in nested models of ModelBuilder?October 22

    I have a model that consists of two nested models and various parameters. There are two parameters that are common to all of the models (including the overall "grand" model). The common parameters are in-line variables and serve to assign unique

  • Creating Instance of Nested model inside parent controllerJanuary 18

    I would like to know if it is possible to create an instance of a nested model inside the parents controller. Let me explain. I have a model called Museum and another model called Museumimage. Museumimage has only one field which is an attachment, ma

  • Knockout JS Mapping fromJS nested modelsJanuary 27

    I am having trouble understanding how to work with Knockout JS Mapping Plugin. I have some nested models (as seen below) and what I am currently doing is just using the ko.mapping.fromJS() in the parent model. What I am noticing is that computed valu

  • Trying to update nested model first on before_saveFebruary 11

    I am calculating :price in my nested item model in order to map it in my invoice model. The problem is that the before_save in the invoice model is being called first and I want it to be called after the before_save in the nesteditem model Any ideas

  • form validation with nested models in Rails

    form validation with nested models in RailsJanuary 22

    I have this problem. I need to validate the attributes of two models in the same form in Rails. One is the parent of the other. The form is like this: <%= semantic_form_for @professional do |pro| %> <%= pro.inputs :id => "information"

  • Creating nested models in Rails 4 forum appJanuary 31

    Hello I am making a Forum application in Rails 4. It can have numerous forums, each with numerous topics. Each topic can have many posts. When creating a new topic, one must also create the initial post, much like Stack Overflow itself. Therefore, I

  • Rails Active model validator not accepting :on = :createJanuary 20

    I have a User model and for that i have used a custom validator class and the code for custom validator class is given as user_validator.rb class UserValidator include ActiveModel::Validations attr_accessor :first_name, :last_name, :email, :id valida

  • Rails how to create select dropdown with double nested model?January 19

    I'm new to Rails and I'm trying to create a select dropdown for menu items. The complicated part is each Restaurant has many Categories which have many menu items. My goal is to have a dropdown that prints something like the following: <optgroup labe

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.418 s.