Query with date ranges

Ecto for Beginners : part 12 of 22 published on Sep 06, 2015

defmodule Readdit.Posts.WherePostedOnTest do use ExUnit.Case use Readdit.ConnCase import Ecto.Query

setup do

%Readdit.Post{
  title: "Han Shot First", 
  posted_on: Ecto.DateTime.from_erl({{2015, 5, 8}, {10,0,0}})
} |> Readdit.Repo.insert!

%Readdit.Post{
  title: "Tony Stark is Iron Man", 
  posted_on: Ecto.DateTime.from_erl({{2015, 9, 12}, {10,0,0}})
} |> Readdit.Repo.insert!

%Readdit.Post{
  title: "The enemy's gate is down", 
  posted_on: Ecto.DateTime.from_erl({{2013, 1, 4}, {10,0,0}})
} |> Readdit.Repo.insert!

:ok

end

test “where posted_on == date |> all” do

posts = Readdit.Post
|> where([p], p.posted_on == ^Ecto.DateTime.from_erl({{2015, 5, 8}, {10,0,0}}))
|> Readdit.Repo.all

assert Enum.count(posts) == 1

end

test “where posted_on > 1/1/2015 |> all” do

posts = Readdit.Post
|> where([p], p.posted_on > ^Ecto.DateTime.from_erl({{2015, 1, 1}, {0,0,0}}))
|> Readdit.Repo.all

assert Enum.count(posts) == 2

end

test “where posted_on < 1/1/2015 |> all” do

posts = Readdit.Post
|> where([p], p.posted_on < ^Ecto.DateTime.from_erl({{2015, 1, 1}, {0,0,0}}))
|> Readdit.Repo.all

assert Enum.count(posts) == 1

end

test “where posted_on > 1/1/2015 and posted_on < 6/1/2015 |> all” do

posts = Readdit.Post
|> where([p], p.posted_on < ^Ecto.DateTime.from_erl({{2015, 1, 1}, {0,0,0}}))
|> Readdit.Repo.all

assert Enum.count(posts) == 1

end

end

Next: Update a record