Smokestack factory with belongs_to relationship

I have an Ash resource (say A) that has a relationship to B.

defmodule A do
    use Ash.Resource, data_layer: AshPostgres.DataLayer
    attributes do
        uuid_primary_key :id
        create_timestamp :inserted_at
        update_timestamp :updated_at
        attribute :x, :string, do: allow_nil?(false)
    end
    relationships do  
      belongs_to :b, B
    end
end

defmodule B do
    use Ash.Resource, data_layer: AshPostgres.DataLayer
    attributes do
        uuid_primary_key :id
        create_timestamp :inserted_at
        update_timestamp :updated_at
        attribute :x, :string, do: allow_nil?(false)
    end
end

How do I insert! multiple B and set the belongs_to relationship to an already inserted resource A?

Thanks.

I’m not sure on this one, @jimsynz likely would be able to tell you. Mind adding the ash and smokestack tags so he can find it?

Hi there @tellesleandro :wave:

Okay, let me get this straight. I think your code snippet and your question tell two different stories, so I’ll answer both.

What I see in your code is that A belongs_to B and I presume B has_(one|many) A then when you insert your collection of B (ie insert!(B, count: 3)) then you will need to choose one to relate A to by using an update action to set it’s b_id attribute (either by making the attribute writable or using manage_relationship).

However based on my parsing of your question, I think what you mean is that B belongs_to A and A has_many B in which case you could just set the a_id attribute on B when inserting them - ie insert!(B, count: 3, attrs: %{a_id: a.id}).

Hope one of those is the answer you’re looking for. Feel free to clarify if you need more help.

Thanks @jimsynz.
I think the example I gave is a bit confusing, but I got the point of your answer.
I’ll try and let you know how it goes.