Phoenix Framework:将插入数据库限制为每天一次

Phoenix Framework: limit Insert into database to one per day

我想为这里的工作人员做一个 "daily votation lunch" 应用程序,使用 Phoenix Framework. The model I thought of making was Votation, with each Votation containing many embedded Restaurants schemas (Read here 获取有关嵌入式模式的信息)。该模型看起来像这样:

defmodule WhereToLunch.Votation do
  use WhereToLunch.Web, :model

  schema "votations" do
    embeds_many :restaurants, Restaurant
    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \ %{}) do
    struct
    |> cast(params, [])
    |> validate_required([])
    |> #TODO: Is it !was_votation_inserted_today() ??
  end

  @doc """
  Returns `true` if a `Votation` object was already inserted in the database
  on the same day the function is called. Returns false otherwise.
  """
  def was_votation_inserted_today() do
    #TODO: How to check if a object was already inserted in the database
    #      on the same day the function is called?
  end
end

defmodule WhereToLunch.Restaurant do
  use Ecto.Model

  embedded_schema do
    field :name, :string
    field :votes, :integer, default: 0
  end
end

我想做的是每天 table where_to_launch.votations 中不允许超过一个 Insert。这样做的最佳方法是什么?

我会在表达式 date_part('day', inserted_at) 上添加一个唯一索引,并让数据库处理唯一性。

要创建唯一索引,请将以下内容添加到新迁移中:

def change do
  create index(:posts, ["date_part('day', inserted_at)"], name: "post_inserted_at_as_date", unique: true)
end

然后将 unique_constraint 添加到模型的 changeset/2:

def changeset(...) do
  ...
  |> unique_constraint(:inserted_at, name: "post_inserted_at_as_date")
end

数据库现在不允许在 inserted_at 的同一天创建 2 个帖子:

iex(1)> Repo.insert Post.changeset(%Post{}, %{title: ".", content: "."})
[debug] QUERY OK db=0.3ms
begin []
[debug] QUERY OK db=3.4ms
INSERT INTO "posts" ("content","title","inserted_at","updated_at") VALUES (,,,) RETURNING "id" [".", ".", {{2017, 2, 6}, {16, 58, 0, 512553}}, {{2017, 2, 6}, {16, 58, 0, 517019}}]
[debug] QUERY OK db=0.9ms
commit []
{:ok,
 %MyApp.Post{__meta__: #Ecto.Schema.Metadata<:loaded, "posts">,
  comments: #Ecto.Association.NotLoaded<association :comments is not loaded>,
  content: ".", id: 1, inserted_at: ~N[2017-02-06 16:58:00.512553], title: ".",
  updated_at: ~N[2017-02-06 16:58:00.517019],
  user: #Ecto.Association.NotLoaded<association :user is not loaded>,
  user_id: nil}}
iex(2)> Repo.insert Post.changeset(%Post{}, %{title: ".", content: "."})
[debug] QUERY OK db=0.4ms
begin []
[debug] QUERY ERROR db=6.6ms
INSERT INTO "posts" ("content","title","inserted_at","updated_at") VALUES (,,,) RETURNING "id" [".", ".", {{2017, 2, 6}, {16, 58, 1, 695128}}, {{2017, 2, 6}, {16, 58, 1, 695138}}]
[debug] QUERY OK db=0.2ms
rollback []
{:error,
 #Ecto.Changeset<action: :insert, changes: %{content: ".", title: "."},
  errors: [inserted_at: {"has already been taken", []}], data: #MyApp.Post<>,
  valid?: false>}