validate_uniqueness_of scope не работает

В настоящее время я могу создать один предмет с несколькими дизайнами в уникальных картинках. Создание второго элемента дает мне следующую ошибку, что уже существует 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"

Design.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

item.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 из индекса, потому что, возможно, это было излишним, но это ничего не решило.

1 ответ

Решение

Ваш индекс должен быть

add_index "designs", ["pictureloc", "item_id"], :name => "index_designs_on_pictureloc", :unique => tru
Другие вопросы по тегам