我有三种型号...
class Product
has_many :master_questions
has_many :custom_questions
has_many :rules
has_many :conditions, through: :rules
accepts_nested_attributes_for :custom_questions
accepts_nested_attributes_for :rules
end
class MasterQuestion
has_many :conditions, as: :conditionable
end
class CustomQuestion
belongs_to :product
has_many :conditions, as: :conditionable
end
class Rule
belongs_to :product
has_many :conditions
accepts_nested_attributes_for :conditions
end
class Condition
belongs_to :rule
belongs_to :conditionable, polymorphic: true
end
“我的条件”表中包含以下列:
conditionable_id :uuid
conditionable_type :string
我将Vue用作前端,因此未使用Rails表单,但我希望能够同时创建“自定义问题”和“条件”并进行关联。目前,我是在保存后手动分配ID,但感觉很hacky,并且引起一些副作用。
我的手动分配方法是这样的...
def assign_conditionable_ids
conditions.each do |condition|
conditionable_class = condition.class.name.constantize
conditionable = conditionable_class.find_by(name: condition.conditionable_name)
condition.update(conditionable_id: conditionable.id)
end
end
任何用于处理此问题的最佳做法(保存前分配ID?使用构建方法?还有其他方法?)或者也许有一种方法可以更好地设置关联,参数或控制器,以便我可以自动分配{{ 1}}作为CustomQuestion
Condition
?