Rails,使用build创建一个嵌套对象,但它没有被保存



我的应用程序有三种型号:

Thread (has_many :thread_apps)
ThreadApp (belongs_to :thread, has_many :forms, :as => :appable)
Form (belongs_to :app)
ThreadApp Fields: thread_id, form_id, appable_id, appable_type

我想做的是,在创建表单时,确保同时创建ThreadApp记录以建立关联:

这是我所拥有的:

class FormsController < ApplicationController
 def create
    @thread = Thread.find(params[:thread_id])
    @thread_app = @thread.thread_apps.new
    @form = @thread_app.forms.build(params[:form].merge(:user_id => current_user.id))
    @form.save
    ....

这很好地保存了表单,但相关的thread_app没有制作出来?有什么想法吗?

感谢

调用model.save不会保存关联,除非您将其告知

你可以设置自动保存

class Form < ActiveRecord::Base
   belongs_to :thread_app , :autosave => true
end

或在控制器中调用保存

@thread_app.save

或者你可以把它完全从控制器中取出并使用回调

class Form < ActiveRecord::Base
   before_create :create_thread_app
   def create_thread_app
     self.thread_app ||= ThreadApp.create(...)
   end
end

或在_create之后、_before_validation_o_create或任何其他回调都可以工作

--更新--

使用create-inse=tead of new和指定为"as"的appables可能会有所不同

class FormsController < ApplicationController
 def create
    @thread = Thread.find(params[:thread_id])
    @thread_app = @thread.thread_apps.create
    @form = @thread_app.appables.build(params[:form].merge(:user_id => current_user.id))
    @form.save
    ....

代替:

@thread_app = @thread.thread_apps.new

你应该有:

@thread_app = @thread.thread_apps.create

最新更新