Skip to content

Instantly share code, notes, and snippets.

@ricn
Last active September 26, 2015 21:42
Show Gist options
  • Save ricn/da952009926e7e5ca27a to your computer and use it in GitHub Desktop.
Save ricn/da952009926e7e5ca27a to your computer and use it in GitHub Desktop.
controller code:
def toggle_star(conn, %{"id" => id}) do
bookmark = Repo.one(Bookmark.by_id_and_user_id(id, user_id(conn)))
if bookmark do
Bookmark.changeset(bookmark)
|> put_change(:starred, !bookmark.starred)
|> Repo.update!
render(conn, "toggle_star.json", starred: !bookmark.starred)
end
end
model:
defmodule Bookmarks.Bookmark do
use Bookmarks.Web, :model
schema "bookmarks" do
field :href, :string
field :title, :string
field :description, :string
field :starred, :boolean
field :read_later, :boolean
belongs_to :user, User
timestamps
end
@required_fields ~w(href user_id)
@optional_fields ~w(title description starred read_later)
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> validate_length(:title, max: 255)
|> validate_length(:description, max: 2000)
|> validate_format(:href, ~r/(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/)
|> validate_length(:href, max: 2000)
end
def by_id_and_user_id(id, user_id) do
from b in Bookmarks.Bookmark,
where: b.id == ^id and b.user_id == ^user_id,
select: b
end
end
error:
[error] #PID<0.582.0> running Bookmarks.Endpoint terminated
Server: localhost:4000 (http)
Request: POST /bookmarks/7/toggle_star
** (exit) an exception was raised:
** (Ecto.InvalidChangesetError) could not perform update because changeset is invalid.
* Changeset changes
%{starred: true}
* Changeset params
nil
* Changeset errors
[]
(ecto) lib/ecto/repo/model.ex:28: Ecto.Repo.Model.update!/4
(bookmarks) web/controllers/bookmark_controller.ex:48: Bookmarks.BookmarkController.toggle_star/2
(bookmarks) web/controllers/bookmark_controller.ex:1: Bookmarks.BookmarkController.phoenix_controller_pipeline/2
(bookmarks) lib/phoenix/router.ex:265: Bookmarks.Router.dispatch/2
(bookmarks) web/router.ex:1: Bookmarks.Router.do_call/2
(bookmarks) lib/bookmarks/endpoint.ex:1: Bookmarks.Endpoint.phoenix_pipeline/1
(bookmarks) lib/plug/debugger.ex:90: Bookmarks.Endpoint."call (overridable 3)"/2
(bookmarks) lib/phoenix/endpoint/render_errors.ex:34: Bookmarks.Endpoint.call/2
(plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
(cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment