2017-09-28 16 views
0

私はUserモデルとShopモデルを持っています。私は1つのショップしか作成できないようにしたい。だから私のUserモデルhas_one associationは複数のレコードをレールに作成します

class User < ApplicationRecord 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    validates :terms_and_conditions, :acceptance => true 
    has_one :shop 
end 

そして、私の店のモデルに私はすでに1店を持つユーザーのための新しいお店を作成しようとすると、エラーがないこの

class Shop < ApplicationRecord 
    has_many :products, dependent: :destroy 
    belongs_to :user 
end 

のように見えますが、コンソールから正常にコミットします。

[ 
    #<Shop id: 1, name: "Rabin & Rose Shop", location: "Banepa Kavre Nepal", description: "oho k vhk kl;o jjio ko;k; jljlkj", rating: nil, delivery_service: true, user_id: 1, created_at: "2017-09-27 15:31:57", updated_at: "2017-09-27 15:31:57", img_url: nil>, 
    #<Shop id: 2, name: "jhoney", location: "sins shop", description: "the entire fuck history here", rating: nil, delivery_service: true, user_id: 1, created_at: "2017-09-28 00:55:44", updated_at: "2017-09-28 00:55:44", img_url: nil>, 
    #<Shop id: 3, name: "Thakur Shop", location: "Pulbazar banepa", description: "Our shop has chicken bedroom. you can met call gir...", rating: nil, delivery_service: true, user_id: 2, created_at: "2017-09-28 01:50:40", updated_at: "2017-09-28 01:50:40", img_url: nil>, 
    #<Shop id: 4, name: nil, location: nil, description: nil, rating: nil, delivery_service: true, user_id: 1, created_at: "2017-09-28 03:49:34", updated_at: "2017-09-28 03:49:34", img_url: nil> 
] 

user_id = 1には複数のレコードがあります。

答えて

1

Rails関連メソッド(has_onehas_manyなど)は、データを検証しません。つまり、アプリケーションレイヤーまたはデータレイヤーで受信データにバリデーションを設定していないため、データを挿入することができます。

ユーザが複数のショップを持つことを制限するには、データレイヤに一意のインデックスを追加し、必要に応じてアプリケーションレイヤで一意性の検証を追加する必要があります。それがいったん成立すると、特定のユーザーに対して複数のショップを作成することはできません。

移行に一意索引が、そのインデックスを使用してこの

add_index :shops, :user_id, unique: true 

ようになるはずです、データベースは、お店のレコードが重複user_idで挿入することはできません。アプリケーション層で

、あなたはShopに、ユーザーまたはuser_idの上で一意性の検証をアドオンまたはshopの存在を確認し、検証が失敗した場合、それはエラーを追加する必要がありUserの検証を追加することができます。

この

は、あなたが何をしたい達成するために、多くの解決策のうちの1つにすぎないこと

class Shop < ApplicationRecord 
    validate :one_shop_per_user 

    private 

    def one_shop_per_user 
    if user.shop && user.shop != self 
     errors.add(:user, "already has a shop") 
    end 
    end 
end 

注意の一例です。

関連する問題