Since we added the relation in this file, I also need to specify it in `lib/tutorial/products/product.ex` and add: That means that if the database raises an error on this index, Ecto will rescue it and return it as a more friendly validation error. **Note**: Since I added the constraint in the migration, the database has given it the name: `variants_name_value_product_id_index` so I will specify it here. |> unique_constraint(:name, name: :variants_name_value_product_id_index) Add in the changeset: `|> unique_constraint(:name, name: :variants_name_value_product_id_index)` Change `field :product_id, :id` to `belongs_to :product, `Ģ. Open `lib/tutorial/products/variant.ex` andġ. I also want to make sure that I have defined the unique constraint in the changeset. In the `Variant` module, I can define the relation to the product. # STEP 2 - Make validations and associations work So, the migration ends up something like:ĭdefmodule doĪdd :product_id, references(:products, on_delete: :delete_all)Ĭreate unique_index(:variants, ) **I want the unique index because I don't want a product having same name and value twice.**īut I don't want to allow this combination twice: Add a unique index `unique_index(:variants, )` Change `on_delete: :nothing` to `n_delete: :delete_all`Ģ. Open up the migration file that should look like this:ĭefmodule doĪdd :product_id, references(:products, on_delete: :nothing)ġ. When I delete a product, I want the database to remove the references variants as well. It means that there cant exist a variant pointing to a product that doesn't exist. Note that I use a database constraint on product_id. I wan't them in the same context, so I will just go agead and press Y Mix Products Variant variants product_id:references:products name value I will start with generationg `variants` and I do it in the same context as the `products`. I will to it by adding variants to products. In this short tutorial, I will go through my usual steps regarding setting up a basic has_many / belongs_to - relation. And even though Phoenix comes with generators for migrations and CRUD operations, you still need to modify the code to suite for the relations you want. Something I do in EVERY project is to setup some sort of relation between resources.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |