我的模型和它的关联是:导轨 - 避免关联自动保存
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
validates :commenter, :presence => true
end
案例1:当我尝试下面的代码自动保存方法被调用。
@post = Post.find(3)
@comments = @post.comments
p @comments #=> []
p @comments.class #=> Array
if @comments.empty?
3.times do
@comments << @post.comments.build
end
end
p @comments.first.errors #=>{:commenter=>["can't be blank"]}
案例2:如果我手动初始化同一空数组到@comments,自动保存并没有叫。例如,
p @comments #=> []
p @comments.class #=> Array
if @comments.empty?
@comments = []
p @comments #=> []
3.times do
@comments << @post.comments.build
end
end
p @comments.first.errors #=>{}
什么是避免自动保存,并请任何一个解释为什么上面的代码不同的表现最佳的解决方案?
@ dimuch-:给了明确的解释和工作液的感谢。 –