【发布时间】: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