2011-06-27 12 views
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記錄還創建使聯想:

以下是我有:

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沒有被提出?任何想法爲什麼?

謝謝

回答

3

的召喚,除非你告訴它

您可以設置自動保存

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

或致電其保存在控制器model.save不保存協會

@thread_app.save 

或者你可以把它拿出來控制整個的LY 併爲此與一個回調

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

或after_create,_before_validation_on_create,或其他任何回調將工作

- UPDATE -

這可能使用創建櫻雪有所作爲= tead of new,並且appables您指定爲'as'

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 
    .... 
+0

感謝。自動保存不會出現是具有 – AnApprentice

+0

你能在我應如何建立表單對象建議有什麼影響? – AnApprentice

+0

嘗試將自動保存在其他物體上,看在未保存的對象http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html部分 – loosecannon

2

相反的:

@thread_app = @thread.thread_apps.new 

你應該有:

@thread_app = @thread.thread_apps.create