私は「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のデータベースを使用しています。
これらのFKは、参照整合性を強制する必要があります。これらの無効な行を有効と見なすのは誰ですか?なぜ、 'recipe_id'と' ingredient_id'カラムも 'not null'でないのですか? –
有効とはどういう意味ですか?モデルに有効であると表示されている場合は、そこに検証がないので、それをdbに挿入できるわけではありません。 – Iceman
うわー、私は馬鹿だと感じる。私は '.valid? 'を使っていましたが、もちろんモデルのバリデーションだけを実行します。私はdbに保存しようとすると正しく動作します。ありがとう@Iceman :-) –