Kapeusz

Kapeusz

Image upload using Arc and nested form

Hi,

I have two models, Product and Category. After help I got from here I could add/edit a product with the chosen category, but now after I set up Arc I face same error again: assign @categories not available in eex template, when I try to add or edit a product. Anyone has an idea what I could have done wrong?

My schemas:

      schema "products" do
        field :avdate, :date
        field :description, :string
        field :name, :string
        field :price, :float
        field :prodimg, ShopifyWeb.DisplayImage.Type
        field :quantity, :integer
        field :subcategory, :integer
        belongs_to :category, Shopify.Departments.Category
        has_many :comments, Shopify.Reviews.Comment
        timestamps()
      end
    
      @doc false
      def changeset(product, attrs) do
        product
        |> cast(attrs, [:name, :quantity, :price, :subcategory, :description, :avdate, :category_id])
        |> cast_attachments(attrs, [:prodimg])
        |> validate_required([:name, :quantity, :price, :subcategory, :description, :avdate, :category_id])
    
      end
 ---
      schema "categories" do
        field :name, :string
        field :subcategory, :string
        has_many :products, Shopify.Inventory.Product
        timestamps()
      end
    
      @doc false
      def changeset(category, attrs) do
        category
        |> cast(attrs, [:name, :subcategory])
        |> validate_required([:name, :subcategory])
      end
New/Edit in product controller:

      def new(conn, _params) do
        changeset = Inventory.change_product(%Product{})
        categories = Repo.all(Category) |> Enum.map(&{&1.name, &1.id})
        render(conn, "new.html", changeset: changeset, categories: categories)
      end
    
      def create(conn, %{"product" => product_params}) do
        case Inventory.create_product(product_params) do
          {:ok, product} ->
            conn
            |> put_flash(:info, "Product created successfully.")
            |> redirect(to: Routes.product_path(conn, :show, product))
    
          {:error, %Ecto.Changeset{} = changeset} ->
            render(conn, "new.html", changeset: changeset)
        end
      end
    
      def show(conn, %{"id" => id}) do
        product = Inventory.get_product!(id)
    
        comment_changeset = Reviews.change_comment(%Comment{})
        render(conn, "show.html", product: product, comment_changeset: comment_changeset)
      end
    
      def edit(conn, %{"id" => id}) do
        product = Inventory.get_product!(id)
        changeset = Inventory.change_product(product)
        categories = Repo.all(Category) |> Enum.map(&{&1.name, &1.id})
        render(conn, "edit.html", product: product,  changeset: changeset, categories: categories)
      end
    
      def update(conn, %{"id" => id, "product" => product_params}) do
        product = Inventory.get_product!(id)
    
        case Inventory.update_product(product, product_params) do
          {:ok, product} ->
            conn
            |> put_flash(:info, "Product updated successfully.")
            |> redirect(to: Routes.product_path(conn, :show, product))
    
          {:error, %Ecto.Changeset{} = changeset} ->
            render(conn, "edit.html", product: product, changeset: changeset)
        end
      end

My image uploader:

      @acl :public_read
      @versions [:primary, :thumbnail]
    
      def transform(:primary, {_file, _product}) do
        {:convert, "-resize 50%"}
      end
    
      def transform(:thumbnail, {_file, _product}) do
        {:convert, "-resize 25%"}
      end
    
      def validate({file, _product}) do
        file_extension = file.file_name
        |> Path.extname()
        |> String.downcase()
    
        Enum.member?([".png"], file_extension)
      end
    
      def s3_object_headers(:primary, {file, _product}) do
        %{content_type: MIME.from_path(file.file_name)}
      end
    
    
    
    
      def default_url(:primary, _product) do
        "http://placehold.it/350x200"
      end
    
      def default_url(:thumbnail, _product) do
        "http://placehold.it/175x100"
      end
    
    end

Display image in product_view.ex

      def display_image(product, version) do
        {product.prodimg, product}
        |> DisplayImage.url(version)
        |> img_tag()
      end
    end

And my product form

    <%= form_for @changeset, @action, [multipart: true], fn f -> %>
      <%= if @changeset.action do %>
        <div class="alert alert-danger">
          <p>Oops, something went wrong! Please check the errors below.</p>
        </div>
      <% end %>
    
      <%= label f, :name %>
      <%= text_input f, :name %>
      <%= error_tag f, :name %>
    
      <%= label f, :quantity %>
      <%= number_input f, :quantity %>
      <%= error_tag f, :quantity %>
    
      <%= label f, :price %>
      <%= number_input f, :price %>
      <%= error_tag f, :price %>
    
      <div class="form-group">
        <%= select f, :category_id, @categories %>
        <p class="help is-danger"><%= error_tag f, :category %></p>
      </div>
    
    
      <%= label f, :subcategory %>
      <%= number_input f, :subcategory %>
      <%= error_tag f, :subcategory %>
    
      <%= label f, :description %>
      <%= text_input f, :description %>
      <%= error_tag f, :description %>
    
      <%= label f, :avdate %>
      <%= date_select f, :avdate %>
      <%= error_tag f, :avdate %>
    
        <div class="form-group">
          <%= label f, :prodimg, class: "control-label" %>
          <%= file_input f, :prodimg, class: "form-control" %>
          <%= error_tag f, :prodimg %>
        </div>
    
    
      <div>
        <%= submit "Save" %>
      </div>
    <% end %>

Marked As Solved

kokolegorille

kokolegorille

Whenever You fail to create, or update, You rerender new.html, or update.html, but You don’t pass categories. So the template is not happy…

Like here… no categories are passed to the template. That’s why You have this error.

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement