A polymorphic association and a foreign key reference can refer to the same table. How to create a new object?

A simplified example of what I have,

class Apple < ActiveRecord::Base
  has_many :bananas, as: :bananable, dependent: destroy
  has_many :bananas
end

class Orange < ActiveRecord::Base
  has_many :bananas, as: :bananable, dependent: destroy
end

class Banana < ActiveRecord::Base
  belongs_to :bananable, polymorphic: true
  belongs_to :apple
end

Thus, a banana can belong to either Apple or Orange as a banal, but will belong to Apple through an external key relationship independently. It may seem a little forced in the context of fruit, but the actual models are quite complex, so I simplified the situation. Basically, a polymorphic association defines the area in which Banana exists, but Banana is part of Apple regardless of its area.

The problem I am facing is when I try to create a new banana. For example:

@Apple.bananas.new(valid_params)

apple_id , (bananable_id bananable_type). , : , , .

?

, - :

@banana = @Apple.bananas.new(valid_params)
@Apple.bananables << @banana

@banana = @Apple.bananas.new(valid_params)
@Orange.bananables << @banana

, ,

@banana = @Apple.bananas.new(valid_params)
if params.has_key?(:orange_id)
  @banana.bananable = @orange
else
  @banana.bananable = @apple
end
@banana.save
+4
2

: inverse_of Banana. , Rails , , , - . , .

belongs_to :bananable, polymorphic: true, inverse_of: :bananas

Rails , .

, . save! , , .

+1

, . Ruby on Rails Guide "with polymorphic associations, a model can belong to more than one other model, on a single association".

, . , banana apple, bananable_id bananable_type , apple_id - .

, . , .

class Apple < ActiveRecord::Base
  has_many :bananas, as: :bananable, dependent: destroy
end

class Orange < ActiveRecord::Base
  has_many :bananas, as: :bananable, dependent: destroy
end

class Banana < ActiveRecord::Base
  belongs_to :bananable, polymorphic: true
end

- , , , .

0

Source: https://habr.com/ru/post/1608900/


All Articles