Putting ecto struct on conn, Good Practice?

I have a lot of resources nested under 1 common resource. For example a blog hosting site which has the following resources:

    resources "/blogs", BlogController do
        resources "/comments", CommentController
        resources "/posts", PostController
        resources "/users", UserController
    end

In just about every request I need the blog struct, rather than adding “blog_id” => blog_id in all the controller signatures then making a db call I thought it might be wise to have some plug middle-wear to put the blog struct on conn.

Is this concept a good idea or is there a better practice?

I don’t know if this is a good idea, but I have done something similar in one project, and found it to work well in my case. I only have one nested resource though. For this reason, I have defined the plug as a function in controller for the nested resource, e.g.:

defmodule MyApp.CommentController do
  ...
  plug(:assign_blog)
  ...
  case Blogs.get_blog(conn.params["blog_id"]) do
      %Blog{} = blog ->
        assign(conn, :blog, blog)

      nil ->
        raise Error.exception("Blog not found", 404)
    end
    ...
end

If you have several controllers which need the blog resource, then I’d suggest putting that function in a dedicated module (like a “real” plug).

I actually just stumbled upon this blog post which shows how to do it in more detail: https://leejarvis.me/posts/2020/phoenix-simplify-nested-resources