如何使用参数创建依赖的has-one关系

时间:2014-09-16 12:40:07

标签: ruby-on-rails polymorphic-associations

Rails - Best-Practice: How to create dependent has_one relations

与上述问题类似。我有一个记录,我希望有一个(多态关系),但一个"默认"依赖对象不足够吗?我能找到的最接近的是Is it possible to pass params from to a before_create in a model?,但由于它的票数很低而且很笨重,所以我不确定它是"对"溶液

class A < ActiveRecord::Base
  has_one :b, :as=>:foo, :dependent=>:destroy
  accepts_nested_attributes_for :b

end

class B < ActiveRecord::Base
  belongs_to :foo, polymorphic:  true
end

1 个答案:

答案 0 :(得分:0)

通常,这将从accepts_nested_attribute_for创建,如您所示,假设从表单传递。您可以尝试自定义的验证

validate :check_has_b

def check_has_b
  unless b and b.valid?
    errors.add(:base, "You must have a valid B ")
  end
end