如何保存没有相关记录的对象

时间:2014-12-08 13:02:07

标签: ruby-on-rails ruby ruby-on-rails-3

我的模型中有很多关联。每次保存父级时,都会保存与父对象关联的每个记录。这是我想要的行为,而不是每一次。是否有一种特殊的方法来保存“母亲”。对象

5 个答案:

答案 0 :(得分:0)

以下是不确定这是您要找的样品吗?

class Survey < ActiveRecord::Base
  has_many :questions, :dependent => :destroy
  accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end

class Question < ActiveRecord::Base
  belongs_to :survey
  has_many :answers, :dependent => :destroy
  accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end

这里调查有很多问题,所以我从你的问题中假设当调查建立时问题不应该保存?现在让我们来看看Survey的控制器。

surveys_controller.rb

def new
  @survey = Survey.new
  @survey.build  # here I have commented below lines which create the object for questions also
 # 3.times do
 #   question = @survey.questions.build
 #   4.times { question.answers.build }
 # end
end

def create
    @survey = Survey.new(params[:survey])
    if @survey.save
      flash[:notice] = "Successfully created survey."
      redirect_to @survey
    else
      render :action => 'new'
    end
end

答案 1 :(得分:0)

据我所知,默认情况下,如果您保存父类(模型),则不会保存belongs_to关联。

要启用此功能,您需要autosave

例如

class Post < ActiveRecord::Base
  has_one :author, autosave: true
end

然而,进一步观察我发现这种默认行为因不同的关联而异。看看这个答案:When will ActiveRecord save associations?

答案 2 :(得分:0)

可以按每个关联打开或关闭自动保存关联模型的功能,例如:

class Post < ActiveRecord::Base
  has_one :author, autosave: false
  has_many :things, autosave: false
end

在此处阅读所有相关内容:https://api.rubyonrails.org/classes/ActiveRecord/AutosaveAssociation.html

答案 3 :(得分:0)

也许是您模型中的accepts_nested_attributes_for。我也有同样的问题。我将其设置为save: false,但这没有任何意义。我删除了accepts_nested_attributes_for,然后说得通。希望对您有帮助。

答案 4 :(得分:-1)

不幸的是,没有这样的功能。

如果是has_many关联,如果子项为#new_record?,子项将在保存其父项时保存。

如果只是在控制器中修改了params,我会避免保存它。

相关问题