Rails nested fields_for duplicate records in DB

user3129410
  1. Question is how to refactor _form.html.erb to properly save all data to the db without duplicating entrie.
  2. The problem is when trying to create new row in a valuation line rails save in one row valuation_id, part_id and another row valuation_id and pruchase_price. Kind of duplicating rows whereas it should merge all this data in one row.

The situation is I have a valuation model which has many valuation_lines. The goal of this program is to prepare a valuation (offer) with multiple parts (items on it). I am using a join table valuation_lines which stores every line of differrent valuations. (To keep things simple at this moment i have a form with only one valuation line).

ps. I went through all railscast on nested models... :(

My valuation form looks like:

   <%= form_for(@valuation) do |f| %>
  <% if @valuation.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@valuation.errors.count, "error") %> prohibited this valuation from being saved:</h2>

      <ul>
      <% @valuation.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>

      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>
<div class="field">

</div>
<div class="field">

<%= f.fields_for :valuation_lines do |builder| %>

<%= f.collection_select(:part_ids, @parts, :id, :name) %><br/>
      <%= builder.label :pruchase_price, "Price:" %> <br/>
      <%= builder.text_field :pruchase_price %>
<% end %>

</div>    

<div class="field">
<br>  
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

valuations_controller.rb

class ValuationsController < ApplicationController
  before_action :set_valuation, only: [:show, :edit, :update, :destroy]

  # GET /valuations
  # GET /valuations.json
  def index
    @valuations = Valuation.all
  end

  # GET /valuations/1
  # GET /valuations/1.json
  def show
  end

  # GET /valuations/new
  def new
    @valuation = Valuation.new
    @parts = Part.all
    @valuation.valuation_lines.build
  end

  # GET /valuations/1/edit
  def edit
  end

  # POST /valuations
  # POST /valuations.json
  def create
    @valuation = Valuation.new(valuation_params)

    respond_to do |format|
      if @valuation.save
        format.html { redirect_to @valuation, notice: 'Valuation was successfully created.' }
        format.json { render action: 'show', status: :created, location: @valuation }
      else
        format.html { render action: 'new' }
        format.json { render json: @valuation.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /valuations/1
  # PATCH/PUT /valuations/1.json
  def update
    respond_to do |format|
      if @valuation.update(valuation_params)
        format.html { redirect_to @valuation, notice: 'Valuation was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @valuation.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /valuations/1
  # DELETE /valuations/1.json
  def destroy
    @valuation.destroy
    respond_to do |format|
      format.html { redirect_to valuations_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_valuation
      @valuation = Valuation.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def valuation_params
       params.require(:valuation).permit(:description, :part_id, :valuation_id, :pruchase_price, :valuation_line, :quantity, :part_ids, parts_attributes: [:id, :code, :name], valuation_lines_attributes: [:id, :valuation_id, :part_id, :pruchase_price, :quantity])

  end
end

Valuation Model

 class Valuation < ActiveRecord::Base
        has_many :valuation_lines
        has_many :parts, :through => :valuation_lines
        accepts_nested_attributes_for :parts
        accepts_nested_attributes_for :valuation_lines

    end

Valuation_line model

class ValuationLine < ActiveRecord::Base
    belongs_to :part
    belongs_to :valuation
end

Part model

class Part < ActiveRecord::Base
    has_many :valuation_lines
    has_many :valuations, :through => :valuation_lines
end

schema_db:

  create_table "parts", force: true do |t|
    t.string   "code"
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "valuation_lines", force: true do |t|
    t.integer "valuation_id"
    t.integer "part_id"
    t.integer "pruchase_price"
    t.integer "quantity"
  end

  create_table "valuations", force: true do |t|
    t.text     "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

development log after adding new valuation returns:

Started POST "/valuations" for 127.0.0.1 at 2014-08-20 22:08:46 +0200
Processing by ValuationsController#create as HTML
  Parameters: {"utf8"=>"✓", 
"authenticity_token"=>"6ADrGOl39bdD3FExQj0l405SXKgJ2zwCqVi6p+JQFw4=", "valuation"=>{"description"=>"33", "part_ids"=>"1"}, "valuation_lines"=>{"pruchase_price"=>"888"}, "commit"=>"Create Valuation"}
  [1m[36mPart Load (38.0ms)[0m  [1mSELECT "parts".* FROM "parts" WHERE "parts"."id" = ? LIMIT 1[0m  [["id", 1]]
  [1m[35m (0.0ms)[0m  begin transaction
  [1m[36mSQL (29.0ms)[0m  [1mINSERT INTO "valuations" ("created_at", "description", "updated_at") VALUES (?, ?, ?)[0m  [["created_at", Wed, 20 Aug 2014 20:08:46 UTC +00:00], ["description", "33"], ["updated_at", Wed, 20 Aug 2014 20:08:46 UTC +00:00]]
  [1m[35mSQL (0.0ms)[0m  INSERT INTO "valuation_lines" ("part_id", "valuation_id") VALUES (?, ?)  [["part_id", 1], ["valuation_id", 59]]
  [1m[36m (76.0ms)[0m  [1mcommit transaction[0m
Redirected to http://localhost:3000/valuations/59
Completed 302 Found in 262ms (ActiveRecord: 143.0ms)
user3129410

Finally figured it out. To avoid duplicate entries simply needed reaarange _form.html.erb like this:

<div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>

  <div class="field">

  <%= f.fields_for :valuation_lines do |builder| %>

      <%= builder.collection_select(:part_id, @parts, :id, :name) %><br/>
      <%= builder.label :pruchase_price, "Price:" %> <br/>
      <%= builder.text_field :pruchase_price %>

  <% end %>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

rails fields_for and nested attributes

From Dev

rails fields_for nested objects

From Dev

Rails fields_for and not creating relationship with nested object

From Dev

Rails 4 nested fields_for not saving

From Dev

Form with nested fields_for which saves to multiple records

From Dev

Rails 3.2 fields_for adding instead of updating records

From Dev

Rails 4 controller actions for fields_for nested resources

From Dev

Rails 4 Nested Attributes with fields_for Don't Save to Database

From Dev

Rails 4 controller actions for fields_for nested resources

From Dev

Updating nested fields_for and collection_select in Rails

From Dev

Rails 5 - has_many through: and nested fields_for in forms

From Dev

Rails Nested Form Error Creates Duplicate Fields

From Dev

Rails 4: fields_for in fields_for

From Dev

Rails Active::Records creates incomplete nested records, when duplicate field detected

From Dev

fields_for a nested resource not working

From Dev

Retrieving form params in Rails 4 controller using fields_for and accepts_nested_attributes_for

From Dev

Rails fields_for params blank

From Dev

How to prevent duplicate records in Rails

From Dev

Displaying Duplicate Records as One in Rails

From Dev

Get duplicate records with group rails

From Dev

Rails fields_for in fields_for rows not associating with parent id

From Dev

Fields_for form fields not displaying in rails form

From Java

Rails - Nested includes on Active Records?

From Dev

Creating nested records on create with Rails

From Dev

Viewing Nested Records in Rails Console

From Dev

Ignore duplicate records in SSIS' OLE DB destination

From Dev

How to set the right index on nested fields_for?

From Dev

Rails: Change class of div generated by fields_for

From Dev

Rails 4 unpermitted parameter using fields_for ?

Related Related

  1. 1

    rails fields_for and nested attributes

  2. 2

    rails fields_for nested objects

  3. 3

    Rails fields_for and not creating relationship with nested object

  4. 4

    Rails 4 nested fields_for not saving

  5. 5

    Form with nested fields_for which saves to multiple records

  6. 6

    Rails 3.2 fields_for adding instead of updating records

  7. 7

    Rails 4 controller actions for fields_for nested resources

  8. 8

    Rails 4 Nested Attributes with fields_for Don't Save to Database

  9. 9

    Rails 4 controller actions for fields_for nested resources

  10. 10

    Updating nested fields_for and collection_select in Rails

  11. 11

    Rails 5 - has_many through: and nested fields_for in forms

  12. 12

    Rails Nested Form Error Creates Duplicate Fields

  13. 13

    Rails 4: fields_for in fields_for

  14. 14

    Rails Active::Records creates incomplete nested records, when duplicate field detected

  15. 15

    fields_for a nested resource not working

  16. 16

    Retrieving form params in Rails 4 controller using fields_for and accepts_nested_attributes_for

  17. 17

    Rails fields_for params blank

  18. 18

    How to prevent duplicate records in Rails

  19. 19

    Displaying Duplicate Records as One in Rails

  20. 20

    Get duplicate records with group rails

  21. 21

    Rails fields_for in fields_for rows not associating with parent id

  22. 22

    Fields_for form fields not displaying in rails form

  23. 23

    Rails - Nested includes on Active Records?

  24. 24

    Creating nested records on create with Rails

  25. 25

    Viewing Nested Records in Rails Console

  26. 26

    Ignore duplicate records in SSIS' OLE DB destination

  27. 27

    How to set the right index on nested fields_for?

  28. 28

    Rails: Change class of div generated by fields_for

  29. 29

    Rails 4 unpermitted parameter using fields_for ?

HotTag

Archive