0

目前,我可以在独特的图片中创建一个具有多种设计的项目。创建第二个项目会给我以下错误,即已经存在具有该值的 pictureloc,即使它位于单独的 item_id 中并且不应该担心。这是我的第一个问题,所以让我在格式上有所懈怠,提前致谢!

错误:

PG::Error: ERROR:  duplicate key value violates unique constraint "index_designs_on_pictureloc"
DETAIL:  Key (pictureloc)=(1) already exists.
: INSERT INTO "designs" ("created_at", "item_id", "picture_content_type", "picture_file_name", "picture_file_size", "picture_updated_at", "pictureloc", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"

设计.rb

class Design < ActiveRecord::Base
  attr_accessible :picture, :pictureloc

  has_attached_file :picture, styles: {medium: "150x150#"}
  validates_attachment :picture, presence: true,
          content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/png'], :message         => 'must be a PNG, JPG, or JPEG'},
      size: {less_than: 5.megabytes, :message => 'must be less than 5 megabytes'}
  validates_uniqueness_of :pictureloc, scope: :item_id

  belongs_to :item

  def show_location
    if pictureloc == 1
        "Front"
    elsif pictureloc == 2
        "Back"
    elsif pictureloc == 3
        "Left Sleeve"
    elsif pictureloc == 4
        "Right Sleeve"
    end
  end
end

项目.rb

class Item < ActiveRecord::Base
  attr_accessible :price, :make, :amount, :color, :note, :designs_attributes
  validates_presence_of :make, :amount, :color
  validates :amount, :numericality => { :greater_than => 0 }

  belongs_to :quote
  has_many :designs, :dependent => :destroy
  accepts_nested_attributes_for :designs
end

架构中的索引:

 add_index "designs", ["pictureloc"], :name => "index_designs_on_pictureloc", :unique => true

嵌套项目视图:

<!-- item form -->
<%= f.input :make, collection: @types, label: 'Thread Type' %>
<%= f.input :amount, label: 'How Many' %>
<%= f.input :color, collection: @colors %>
<!-- nested form for creating a design of an item -->
<%= f.simple_fields_for :designs, :html => { :multipart => true } do |designform| %>
    <%= render "customdesign", g: designform %>
  <% end %>
<!-- add/remove another design -->  
<%= f.link_to_add "Add Design", :designs %>
<%= f.input :note, :input_html => { :cols => 50, :rows => 3 }, label: 'Special Notes or Requests' %>
<%= f.link_to_remove "Remove" %>

嵌套设计视图:

<!-- upload/remove image form -->
<%= g.select( :pictureloc, { "Front" => 1, "Back" => 2, "Left Sleeve" => 3, "Right Sleeve" => 4 } ) %>
<%= g.file_field :picture %>
<%= g.link_to_remove "Remove" %>

请注意,pictureloc 是一个整数,并且设计会同时保存,这就是我必须创建索引的原因(我认为?)

我尝试unique: true从索引中删除它,因为它可能是矫枉过正,但这并没有解决任何问题。

4

1 回答 1

0

你的索引应该是

add_index "designs", ["pictureloc", "item_id"], :name => "index_designs_on_pictureloc", :unique => tru
于 2013-09-11T19:41:54.243 回答