我在has_many关系上存在验证问题,但是父项不存在。但是,在创建/保存父对象时,我想确保特定的子项(具有某些属性)已经保存。对has_many关联的Rails验证
有一个Parent
对象,has_many
Child
对象。 Child
对象首先被保存到数据库中,因此没有任何对父对象的引用。关联结构是:
Parent
- has_many :children
Child
- someProperty: string
- belongs_to: parent
例如,有三个子对象:
#1 {someProperty: "bookmark", parent: nil}
#2 {someProperty: "history", parent: nil }
#2 {someProperty: "window", parent: nil }
父才有效,如果它包含孩子someProperty history
和window
对象。
p = Parent.new(params[:data])
for type in %w[bookmark_id history_id window_id]
if !params[type].blank?
p.children << Child.find(params[type])
end
end
// save the parent object p now
p.save!
当孩子们被分配到父与<<
,他们没有立即保存为父母的ID不存在:
我为建立父控制器内。而且父母要得救,至少必须有两个孩子。我怎么能解决这个问题?任何输入是受欢迎的。
我喜欢这种方法,因为它保持模型内的逻辑。 send(t)函数在这里做什么?它是否被父对象调用? – Anurag 2010-02-04 07:18:21
是的,因为我们将子类型动态地定义为父对象的访问者(属性),所以我们也需要动态访问它们。这就是为什么我们需要调用父对象的send方法。 – 2010-02-04 11:58:44