【问题标题】:Modifying a list of structs in Phoenix修改 Phoenix 中的结构列表
【发布时间】:2017-04-26 15:02:45
【问题描述】:

我有一个后端显示帖子列表的博客。每个帖子都有一个publish_on 值,它是一个日期时间——如果当前时间晚于publish_on,则帖子处于活动状态(帖子有一个名为active 的布尔虚拟字段)。

当我在 Repo 中查询帖子列表时,我想浏览该列表,如果当前时间在 publish_on 之后,则将 Post 的 active 设置为 true。

最“灵药”的方法是什么? (另外,Elixir 社区的“Pythonic”版本是什么?)

models/post.ex

defmodule MyApp.Post do
  use MyApp.Web, :model

  schema "posts" do
    field :title, :string
    field :content, :text
    field :publish_on, Ecto.DateTime
    field :active, :boolean, virtual: true, default: false

    timestamps()
  end

controllers/post_controller.ex

MyApp.PostController
  def index(conn, _params) do
    query = from p in Post,
    posts = Repo.all(query)

    ###I assume some kind of mapping goes here

    render(conn, "index.html", posts: posts)
  end

模板/post/index.html.eex

<table class="table">
<%= for post <- @posts do %>
    <%= if post.active do %>
      <tr class="published">
    <% else %>
      <tr class="unpublished">
    <% end %>

【问题讨论】:

    标签: elixir phoenix-framework ecto changeset


    【解决方案1】:

    我会使用for 浏览帖子,使用DateTime.compare 比较DateTime.utc_nowpost.publish_on,如果是:gt,请将active 设置为true

    posts = Repo.all(query)
    
    now = DateTime.utc_now
    
    posts = for post <- posts do
      case DateTime.compare(now, post.publish_on) do
        :gt -> %{post | active: true}
        _ -> post
      end
    end
    

    【讨论】:

    • 这正是我想要的。我似乎收到DateTime.compare() 的此错误:no function clause matching in DateTime.compare/2。如果我运行DateTime.compare(now, now),它不会抛出这个,所以我猜它与 post.publish_on 的类型有关。
    • @MarkKaravan 看起来像是Ecto.DateTime。在升级到使用新 DateTime 的版本之前,您可以使用 DateTime.utc_now -> Ecto.DateTime.utcDateTime.compare -> Ecto.DateTime.compare
    【解决方案2】:

    您可以在查询中初始化虚拟字段:

    query = from p in Post, select: %{p | active: (s.publish_on < ^DateTime.utc_now())}
    posts = Repo.all(query)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2017-07-27
    • 2017-02-04
    • 2012-12-25
    相关资源
    最近更新 更多