2017-01-17 9 views
2

私は「The Rails Way」ではなく、DBレベルで参照整合性を強制するために外部キーを追加しようとしています。 recipe_ingredientsという名前の新しいテーブルを作成して、レシピと呼ばれるテーブルと食材と呼ばれるテーブルを参照する外部キーを作成します。移行は、次の成功し、生成外部キーが期待どおりに機能しない

class CreateRecipeIngredients < ActiveRecord::Migration 
    def change 
    create_table :recipe_ingredients do |t| 
     t.references :recipe, null: false 
     t.references :ingredient, null: false 

     t.timestamps null: false 
    end 
    add_foreign_key :recipe_ingredients, :recipes 
    add_foreign_key :recipe_ingredients, :ingredients 
    end 
end 

:ここに私の移行である

              Table "public.recipe_ingredients" 
    Column  |   Type    |       Modifiers       | Storage | Stats target | Description 
---------------+-----------------------------+-----------------------------------------------------------------+----------+--------------+------------- 
id   | integer      | not null default nextval('recipe_ingredients_id_seq'::regclass) | plain |    | 
recipe_id  | integer      |                 | plain |    | 
ingredient_id | integer      |                 | plain |    | 
measurement | character varying   | not null              | extended |    | 
created_at | timestamp without time zone | not null              | plain |    | 
updated_at | timestamp without time zone | not null              | plain |    | 
Indexes: 
    "recipe_ingredients_pkey" PRIMARY KEY, btree (id) 
Foreign-key constraints: 
    "fk_rails_176a228c1e" FOREIGN KEY (recipe_id) REFERENCES recipes(id) 
    "fk_rails_209d9afca6" FOREIGN KEY (ingredient_id) REFERENCES ingredients(id) 

問題、私は無効recipe_idで新しいrecipe_ingredientを作成し、および/またはingredient_idしようとすると、それはまだ考えていることですそれは有効です。これらのフィールドで参照整合性を強制するようにdbを取得するにはどうすればよいですか?私はpostgresqlのデータベースを使用しています。

+0

これらのFKは、参照整合性を強制する必要があります。これらの無効な行を有効と見なすのは誰ですか?なぜ、 'recipe_id'と' ingredient_id'カラムも 'not null'でないのですか? –

+1

有効とはどういう意味ですか?モデルに有効であると表示されている場合は、そこに検証がないので、それをdbに挿入できるわけではありません。 – Iceman

+0

うわー、私は馬鹿だと感じる。私は '.valid? 'を使っていましたが、もちろんモデルのバリデーションだけを実行します。私はdbに保存しようとすると正しく動作します。ありがとう@Iceman :-) –

答えて

1

valid?を呼び出すとモデルで検証が実行されますが、参照整合性チェックが実際にデータベースに挿入されるまでは検証されません。

Rails 5には、モデルにbelongs_toが自動的に存在する必要があります。

class Child < ApplicationRecord 
    belongs_to :parent 
end 

あなたが、私は必ずしもこれが「Railsの道」ではないと言うではないでしょう

belongs_to :parent, required: false 
0

でこれをオプトアウトすることができます。私は、ベルトやサスペンダーを着用するような、FKとモデルバリデーションの使用を考えています。それらの時間のためにあなたは本当にあなたのズボンが落ちるのを望まない。

+1

それは偉大な類推です –

関連する問題