Yof
Yof

Reputation: 23

Use f.select for to choose nested object; Couldn't find Item with ID=1 for Quote with ID=

I have a quote system and I'm choosing Items to add to quotes. quotes and items are associated through a 3rd table (quote_items). I use cocoon gem to create quote.item attributes, which in my case is only item id of the item to be attached to the quote. From there I want to extract all the item attributes that are saved in the DB for the selected item. After trying to create a quote choosing one item I'm getting this error message: Couldn't find Item with ID=1 for Quote with ID= when trying to create the quote.

class Item < ApplicationRecord
  has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

  has_many :quote_items 
  has_many :quotes, through: :quote_items, dependent: :delete_all
  # validates_uniqueness_of :part_num , scope: [:quote_id]  
end

class Quote < ApplicationRecord
  has_many :quote_items
  has_many :items, through: :quote_items, dependent: :delete_all
  accepts_nested_attributes_for :items, allow_destroy: true, reject_if: :all_blank
end

in quotes controller

  def new
    @quote = Quote.new
    @item = @quote.items.build 
  end

  def create
    @quote = Quote.new(quote_params)
    respond_to do |format|
      if @quote.save
        format.html { redirect_to quote_path(@quote) }
        format.json { redirect_to quotes_path, status: :created, location: @quote }
      else
        format.html { redirect_to quotes_path }
        format.json { redirect_to quotes_path, status: :unprocessable_entity }
      end
    end
  end

def quote_params
  params.require(:quote).permit(:name,:company,:email,:quote_num, :quantity, :notes, items_attributes: [:id,:_destroy, :part_num, :description, :price, :lead_time, :quote_quantity])
end

quote form

 <%= f.fields_for :items do |i| %>
   <%= render 'item_fields', :f=> i %>  
 <% end %>   

 <%= link_to_add_association 'Add Part', f, :items, class: "btn btn-primary" %>

_item_fields.html.erb

<div class="nested-fields col-lg-12 col-md-12 col-sm-12 col-xs-12">
  <div class="row">
    <div class="col-lg-3 col-md-3 col-sm-4 col-xs-6 form-font">
      <%= f.select :id, options_from_collection_for_select(Item.all, :id, :part_num), required: true, label: "Part Number" %>
    </div>   
  </div>  
  <div class="row">
    <div class="col-lg-3 col-md-3 col-sm-4 col-xs-6 form-font">
      <%= link_to_remove_association "Remove Part", f, class: "btn btn-danger" %>
    </div>  
  </div><br>  
</div>   

QuoteItem

class QuoteItem < ApplicationRecord
  belongs_to :quote
  belongs_to :item
end

Any ideas what I'm missing?

Thanks!

Upvotes: 0

Views: 73

Answers (0)

Related Questions