Situation:
I have 4 models with relationships like these:
class A < ActiveRecord::Base
belongs_to :b
belongs_to :c
belongs_to :d
end
class B < ActiveRecord::Base
has_many :as, dependent: :destroy
end
class C < ActiveRecord::Base
belongs_to :d
end
class D < ActiveRecord::Base
has_many :cs, dependent: :destroy
end
Problem:
I need to relate model A object a
to model B object b
but I also need to set a position for object a
where to appear in ActiveRecord CollectionProxy when calling b.as
and it won't work. All attempts to add object a
to a certain position in a.bs
result end up with having newly added a
at the end. Is it possible at all? I know there are possibilities for defining ordering in arrays and while querying, but is it possible to define the ordering directly when adding new relationship?
Example:
Model B object b
has 3 model A objects.
b.as
=> #<ActiveRecord::Associations::CollectionProxy [
#<A id: 39038, quantity: 3.0 created_at: "2016-02-01 15:51:26", updated_at: "2016-02-01 15:51:26", d_id: 4144, c_id: nil, b_id: 81218>,
#<A id: 39039, quantity: 2.0, created_at: "2016-02-01 15:51:26", updated_at: "2016-02-01 15:51:26", d_id: 4145, c_id: nil, b_id: 81218>,
#<A id: 39040, quantity: 2.0, created_at: "2016-02-01 15:51:26", updated_at: "2016-02-01 15:51:26", d_id: 4145, c_id: 1590, b_id: 81218>]>
I create fourth model A object a
and I need it to appear on second place when calling b.as
like this:
a = A.create(quantity: 4.0, d: D.find(4144), c: C.find(1612), b: b)
Basically the ordering should be defined like this:
b.as
=>
a1: d_id: 4144, c_id: nil
a2: d_id: 4144, c_id: 1612
a3: d_id: 4145, c_id: nil
a4: d_id: 4145, c_id: 1590
...meaning that every a
object with same d_id
attribute should be grouped together meanwhile having those a
s that have c_id.nil?
in first place.