私は小さなモジュールからモジュールを構成したいと思います。エリクサーとエクトのコードの重複
これは私が今持っているモジュールである。
defmodule Api.Product do
use Ecto.Schema
import Ecto.Changeset
import Api.Repo
import Ecto.Query
@derive {Poison.Encoder, only: [:name, :brand, :description, :image, :rating, :number_of_votes]}
schema "products" do
field :name, :string
field :brand, :string
field :description, :string
field :image, :string
field :rating, :integer
field :number_of_votes, :integer
field :not_vegan_count, :integer
end
def changeset(product, params \\ %{}) do
product
|> cast(params, [:name, :brand, :description, :image, :rating, :number_of_votes, :not_vegan_count])
|> validate_required([:name, :description, :brand])
|> unique_constraint(:brand, name: :unique_product)
end
def delete_all_from_products do
from(Api.Product) |> delete_all
end
def insert_product(conn, product) do
changeset = Api.Product.changeset(%Api.Product{}, product)
errors = changeset.errors
valid = changeset.valid?
case insert(changeset) do
{:ok, product} ->
{:success, product}
{:error, changeset} ->
{:error, changeset}
end
end
def get_product_by_name_and_brand(name, brand) do
Api.Product |> Ecto.Query.where(name: ^name) |> Ecto.Query.where(brand: ^brand) |> all
end
def get_products do
Api.Product |> all
end
end
しかし、私はすべてがbrand
を除きProduct
と同じフィールドのほとんどを持っているProduct
以外の異なるものを持っていると思います。したがって、brand
を除くすべてのフィールドを持つモジュールを作成し、それらのフィールドを含むすべてのモジュールがそのモジュールをフィールドとして持つことをお勧めしますか?ここで
は、すべてのモジュールが含まれます私のモジュールです:
defmodule Api.VeganThing do
use Ecto.Schema
import Ecto.Changeset
import Api.Repo
import Ecto.Query
@derive {Poison.Encoder, only: [:name, :description, :image, :rating, :number_of_votes]}
schema "vegan_things" do
field :name, :string
field :description, :string
field :image, :string
field :rating, :integer
field :number_of_votes, :integer
field :not_vegan_count, :integer
end
end
vegan_things
ために何のデータベーステーブルはありません。しかし、データベーステーブルを持ついくつかの異なるモジュールにはvegan_thing
が含まれます。
これは、Elixirの各モジュールのすべてのフィールドを書き換えるコードの重複を避けるための良い方法ですか?ここで
は私の現在のチェンジです:
defmodule Api.Repo.Migrations.CreateProducts do
use Ecto.Migration
def change do
create table(:products) do
add :name, :string
add :brand, :string
add :description, :string
add :image, :string
add :rating, :integer
add :number_of_votes, :integer
add :not_vegan_count, :integer
end
create unique_index(:products, [:name, :brand], name: :unique_product)
end
end
だから私はvegan_thing
になり、フィールド上のユニークさだけproduct
にあるフィールドを基づかよ。このようなことをすることはできますか?
defmodule Api.Repo.Migrations.CreateProducts do
use Ecto.Migration
def change do
create table(:products) do
add :name, :string
add :vegan_thing, :vegan_thing
end
create unique_index(:products, [:vegan_thing.name, :brand], name: :unique_product)
end
end
または私はproduct
に直接name
フィールドを配置する必要がありますか?ユニークな制約として使用するにはvegan_thing
の代わりに?
['Ecto.Schema.embedded_schema/1'](https://hexdocs.pm/ecto/Ecto.Schema.html#embedded_schema/1)に似ていますか? – mudasobwa