Ruby on rails Rails,使用build创建嵌套对象,但未保存该对象
我的应用程序有三种型号:Ruby on rails Rails,使用build创建嵌套对象,但未保存该对象,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我的应用程序有三种型号: 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记录以进行关联: 以下是我所拥有的:
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
....
类FormsControllercurrent\u user.id))
@表单保存
....
这很好地保存了表单,但是没有创建关联的线程应用程序?你知道为什么吗
谢谢您呼叫
型号。除非您告诉save,否则save
不会保存关联
您可以设置自动保存
class Form < ActiveRecord::Base
belongs_to :thread_app , :autosave => true
end
或者,您可以将其完全从控制器中取出
并通过回调来实现这一点
class Form < ActiveRecord::Base
before_create :create_thread_app
def create_thread_app
self.thread_app ||= ThreadApp.create(...)
end
end
而不是:
@thread_app = @thread.thread_apps.new
你应该:
@thread_app = @thread.thread_apps.create
谢谢autosave似乎没有任何效果。您能建议我如何构建表单对象吗?请尝试将autosave放置在另一个对象上,查看未保存对象上的部分
@thread_app = @thread.thread_apps.new
@thread_app = @thread.thread_apps.create