has_one belongs_to association autosave => true not saving

隐身守侯 提交于 2019-12-10 19:31:43

问题


I have two models

Board
has_one    :pref, :autosave => true,  :dependent => :destroy

Pref

belongs_to :board

The pref object has defaults that are set in the database so no information needs to be used to create the object when the board is created. The ID for the board is in the pref table.

Since the :autosave=> true I thought that when I create and save a new Board object a pref object would be created and saved automatically.

This is not working this way so I must be misunderstanding.

Is there a way to autosave a pref object when a board is saved?

Thank you in advance


回答1:


autosave => true should not create an element for you. The docs say:

If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. If false, never save or destroy the associated object.

You could use a callback to create the pref object when you're creating a new board.

Something along the lines of:

after_create :create_pref

def create_pref
  pref.create!
end


来源:https://stackoverflow.com/questions/5403372/has-one-belongs-to-association-autosave-true-not-saving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!