使用f.select选择嵌套对象;找不到ID = 1的物品,引用ID =

时间:2018-03-19 19:05:31

标签: ruby-on-rails nested apache-cocoon

我有一个报价系统,我选择要添加到引号的项目。引号和项目通过第3个表(quote_items)关联。我使用cocoon gem来创建quote.item属性,在我的例子中,它只是要附加到引用的项目的项目ID。从那里我想提取所选项目的DB中保存的所有项目属性。在尝试创建一个引用选择一个项目后,我收到此错误消息:在尝试创建报价时,无法找到ID = 1的项目ID = 1。

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

在引号控制器

  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

引用表格

 <%= 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

我缺少什么想法?

谢谢!

0 个答案:

没有答案