Hello. I’m new into elixir/phoenix and I love it. I’m still learning and can’t figure how to solve this problem about associations in ecto (mysql).
I’m working on something like this:
Category has_many Propertyname many_to_many Property.
Product many_to_many Property
Example category: drinks->brand->[“coca cola”, “pepsi”]. To create a new product (with some specific properties) under this category, in order to generate a variable number of select inputs (one for each Propertyname with some Properties as options), I feed the form with this function:
def list_category_properties(category_id) do
propertynames = for propertyname <- Repo.preload(get_category!(category_id), :propertynames).propertynames do
%{"propertyname_field"=>"propertyname_" <> Integer.to_string(propertyname.id), "propertyname" => propertyname.name, "properties" => for property <- Repo.preload(get_propertyname!(propertyname.id), :properties).properties do
{property.name, property.id}
end
}
end
end
Example:
properties = [
%{
"properties" => [{"Red", 3}, {"Green", 4}],
"propertyname" => "Color",
"propertyname_field" => "propertyname_1"
}
%{
"properties" => [{"Big", 5}, {"Small", 6}],
"propertyname" => "Size",
"propertyname_field" => "propertyname_2"
}
]
For generating the inputs, in the form I use:
<%= for propertyname <- @properties do %>
<p>
<%= label f, propertyname["propertyname"] %>
<%= select f, String.to_atom(propertyname["propertyname_field"]), propertyname["properties"] %>
</p>
<br/>
<br/>
<% end %>
So when the form is submitted the attr’s in the changeset could be:
%{
....
"propertyname_1" => "3",
"propertyname_2" => "6",
}
I’m not sure if it’s even possible to make it work this way, but the whole thing looks quite bad. I’m reading about Ecto associations and there seems to be a better/standard approach to do things like this. But I feel like trying (without any success) to solve the problem by brute force, because I don’t really understand exactly how should I use those methods to solve this particular problem.
Thank you!