How to set up Phoenix ID

Using the phoenix framework,: :id, :integer will be generated automatically. http://www.phoenixframework.org/docs/ecto-custom-primary-keys

But I want it to not be automatically generated and use a custom id field, for example :id, :string , which is very similar to this. http://ruby-journal.com/how-to-override-default-primary-key-id-in-rails/

to install

 defmodule MyApp.Item do use MyApp.Web, :model # @primary_key {:id, :id, autogenerate: false} schema "items" do field :id, :string, autogenerate: false # some unique id string field :type, :integer 

It raises ** (ArgumentError) field/association :id is already set on schema https://github.com/elixir-lang/ecto/blob/db1f9ccdcc01f5abffcab0b5e0732eeecd93aa19/lib/ecto/schema.ex#L1327

+6
source share
1 answer

There are two problems that I have encountered.

  • Both @primary_key {:id, :id, autogenerate: false} and fields :id sentences cannot be in the schema definition.

This decision

 defmodule MyApp.Item do use MyApp.Web, :model @primary_key {:id, :string, []} schema "items" do # field :id, :string <- no need! 
  1. to avoid id autogeneration i just need to change the migration file

Like this

 defmodule MyApp.Repo.Migrations.CreateItem do use Ecto.Migration def change do create table(:items, primary_key: false) do add :id, :string, primary_key: true 

Finally, I can execute mix ecto.migrate and get the table definition below

 mysql> SHOW CREATE TABLE items; | items | CREATE TABLE `builds` ( `id` varchar(255) NOT NULL, 

The white paper certainly talks about it http://www.phoenixframework.org/docs/ecto-custom-primary-keys

Consider migration first, priv / repo / migrations / 20150908003815_create_player.exs. We need to do two things. The first is to pass the second argument - primary_key: false for the table / 2 function so that it does not create primary_key. Then we need to pass primary_key: true for the add / 3 function for the name field to signal that it will be primary_key.

But in the beginning you don’t need the id column, you just do create table(:items, primary_key: false) during the migration process and edit the schema

 defmodule MyApp.Item do use MyApp.Web, :model # @primary_key {:id, :string, []} @primary_key false # to avoid unnecessary IO scanning schema "items" do # field :id, :string <- no need! 

Although self-fulfilling, thanks anyway

+7
source

All Articles