Rails保存嵌套模型关联,has_many通过

时间:2017-02-02 19:49:23

标签: ruby-on-rails associations

class Task < ActiveRecord::Base 
  belongs_to  :project,                    :inverse_of => :tasks 
  accepts_nested_attributes_for :project 
end
class Project < ActiveRecord::Base  
  belongs_to :workspace,            :inverse_of  => :projects
  has_many :tasks,                  :inverse_of => :project, 
                                    dependent: :destroy,
                                    autosave: true
  accepts_nested_attributes_for :workspace 
end
class Workspace < ActiveRecord::Base
  has_many                  :projects,          inverse_of: :workspace,
                                                dependent: :destroy,
                                                autosave: true
  has_many                  :tasks,             through: :projects
end

我可以保存子对象&#39; project&#39;来自&#39;工作区&#39;。但我无法保存孙子对象的任务&#39;来自&#39;工作区&#39;。怎么了?我怎么能这样做没有额外的&#39; .save&#39;电话?我不想打电话给 @ p.save

####child####
@w = Workspace.first
@p = @w.projects.new(name: "text")

@w.save
@p.new_record? #false, which is ok

###grandchild###
@w = Workspace.first
@p = @w.projects.first
@t = @p.tasks.new(name: "text")

@w.save
@t.new_record? #true, but should've been saved

0 个答案:

没有答案