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