validate_uniqueness_of范围无效

时间:2013-09-11 19:39:18

标签: ruby-on-rails validation scope nested-forms validates-uniqueness-of

目前,我可以在独特的picturelocs中创建一个具有多个设计的项目。创建第二个项目会给我以下错误,即已存在具有该值的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 个答案:

答案 0 :(得分:0)

你的索引应该是

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