1

Postgres DB テーブルの値が一意かどうかを if ステートメントを使用して確認したいと考えています。ユニークな場合は何かを行い、ユニークでない場合は別のことを行います。Ruby on Rails での疑似コードは次のようになります。

if validates_uniqueness_of :number == "true"
    puts "this value is unique and should be added to the DB"
else 
    puts "this value is not unique and should not be added to the DB"
end

このタイプのロジックをモデルまたはコントローラーに実装できますか? はいの場合、どちらがより良い方法ですか? いいえの場合、代わりに何をすべきですか? また、構文はこのようなものにどのように見えるでしょうか?

みんなありがとう!

4

4 に答える 4

4

既存のものを使用できますか? レコードがすでにデータベースにあるかどうかを確認するメソッド。検索したいフィールドのハッシュを取ることができます:

before_create :do_something_if_unique

def do_something_if_unique
  if self.class.exists?(number: number)
    # there is a record that exists with this number
  else
    # there are no records that exist with this number
  end
end
于 2012-11-16T00:28:35.603 に答える
1

列で一意の値を見つけるには、次のようにします。

def self.has_unique_numbers?
    pluck(:number).uniq.count == 1
end

次に、モデルまたはコントローラーで、次のように尋ねることができます。

if YourModel.has_unique_numbers?
    # Some Code
else
    # Some other code
end
于 2012-11-16T00:28:40.790 に答える
0

使用できますfirst_or_create

MyModel.where(number: number).first_or_create!

指定された基準に一致するものが見つからない場合 (より多くの AR メソッドを連鎖させることもできます)、オブジェクトはデータベースに保存されます。モデルに入れるかコントローラーに入れるかは、使用方法によって異なります。どちらでもうまくいくはずです。

于 2012-11-16T00:21:31.953 に答える
0

:validates_uniqueness_ofモデルの検証については、 をご覧ください。データベースの制約を追加するかどうかは、フェンスのどちら側に座っているかによって、多くの議論の余地がある大きな問題です:)

class MyThing < ActiveRecord::Base
   validates :number, :uniqueness => true
end

a = MyThing.create(:number => 1) # will succeeed
b = MyThing.create(:number => 2) # will fail and a.errors will contain more info.
于 2012-11-16T00:22:06.747 に答える