Working with repo from controller

Hello!

I am working on gallery for my application.

I have 2 models:

Gallery
Image

And I need to get gallery (id and path) and images (title and file_name) to use it later.

My current solution - place code in web/controllers/product_gallery.ex

defmodule APP.ProductGallery do

  import Ecto.Query

  alias APP.Repo
  alias APP.Gallery
  alias APP.Image

  def get_gallery_id_and_path(name) do
    query = from g in Gallery, where: g.name == ^name
    Repo.one query
  end

  def get_images_title_and_file_name(gallery_id) do
    query = from i in Image, where: i.gallery_id == ^gallery_id, order_by: i.file_name
    Repo.all query
  end

end

and use it from web/templates/product_gallery/index.html.eex

But I feel that working with repo from controller is poor solution.

How do you solve such problems?

Thanks!

1 Like

There are some problems with your code, I think:

  1. If that module is a controller, usually with will have use App.Web, :controller and will have “Controller” at the end of the module’s name.

  2. It’s totally fine to work with the repo in the controllers. I’ve read the Programming Phoenix book and they use it all the time. I’ve also been doing it in my projects, not problem at all.

EDIT: I misread your question. You want to use it in the templates. Well, you may work with the repo in the controller and send the results to the assign in the conn or place the queries in the respective template’s View and then call them from the template.

2 Likes

Thank you!

I am reading Programming Phoenix, too. Now I noticed that they work with repo from controllers :grinning:

Yes, I forgot use App.Web, :controller and then I have to import Ecto.Query and alias APP.Repo
And about Controller at the end - I used an example from book in “Writing an Authentication Plug”.

So, work with repo can be mixed - functions in models like

  def alphabetical(query) do
    from c in query, order_by: c.title
  end

and functions to work with repo in controllers like

  def get_gallery_id_and_path(name) do
    query = from g in Gallery, where: g.name == ^name
    Repo.one query
  end
1 Like

It’s totally fine to work with Repo in your controllers. After all, you’ll have to query from it in your GET related actions and insert in it in your POST related actions!

1 Like

Thanks!