保存主对象时ActiveRecord是否保存belongs_to关联?

如果我有两个型号:

class Post < ActiveRecord::Base belongs_to :user end 

 class User < ActiveRecord::Base has_many :posts end 

如果我做:

 post = Post.new user = User.new post.user = user post.save 

用户是否也得到了保存,并且在postuser_id字段中正确分配了主键?

ActiveRecord belongs_to关联可以与父模型一起自动保存,但默认情况下该function处于关闭状态。 要启用它:

 class Post < ActiveRecord::Base belongs_to :user, :autosave => true end 

我相信你想:

 class User < ActiveRecord::Base has_many :posts, :autosave => true end 

换句话说,在保存用户记录时,请找出“post”关联另一侧的所有记录并保存。

belongs_to API文档说(Rails 4.2.1):

:autosave

如果为true,则在保存父对象时,始终保存关联对象或在标记为销毁时将其销毁。

如果为false,则永远不要保存或销毁关联对象。

默认情况下,仅保存关联对象(如果它是新记录)。

请注意,accepts_nested_attributes_for将:autosave设置为true。

在您的情况下,用户是新记录,因此将自动保存。

很多人也错过了关于accepts_nested_attributes_for的最后一句话。