修改 Phoenix 中的结构列表
Modifying a list of structs in Phoenix
我有一个博客,其后端显示 Post 的列表。每个 Post 都有一个 publish_on
值,它是一个日期时间——如果当前时间晚于 publish_on
,则 Post 是活动的(Post 有一个布尔值名为 active
) 的虚拟字段。
当我在 Repo 中查询 Post 的列表时,我想遍历该列表,如果当前的 Post 的 active
时间在publish_on
.
之后
最 "Elixirian" 的方法是什么? (另外,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
templates/post/index.html.eex
<table class="table">
<%= for post <- @posts do %>
<%= if post.active do %>
<tr class="published">
<% else %>
<tr class="unpublished">
<% end %>
我会使用 for
浏览帖子,使用 DateTime.compare
比较 DateTime.utc_now
和 post.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
您可以在查询中初始化虚拟字段:
query = from p in Post, select: %{p | active: (s.publish_on < ^DateTime.utc_now())}
posts = Repo.all(query)
我有一个博客,其后端显示 Post 的列表。每个 Post 都有一个 publish_on
值,它是一个日期时间——如果当前时间晚于 publish_on
,则 Post 是活动的(Post 有一个布尔值名为 active
) 的虚拟字段。
当我在 Repo 中查询 Post 的列表时,我想遍历该列表,如果当前的 Post 的 active
时间在publish_on
.
最 "Elixirian" 的方法是什么? (另外,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
templates/post/index.html.eex
<table class="table">
<%= for post <- @posts do %>
<%= if post.active do %>
<tr class="published">
<% else %>
<tr class="unpublished">
<% end %>
我会使用 for
浏览帖子,使用 DateTime.compare
比较 DateTime.utc_now
和 post.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
您可以在查询中初始化虚拟字段:
query = from p in Post, select: %{p | active: (s.publish_on < ^DateTime.utc_now())}
posts = Repo.all(query)