Reputation: 110960
My app has three models:
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
What I want to be able to do is when creating a form, ensure that a ThreadApp record is also created to make the association:
Here is what I have:
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
....
This is saving the form nicely, but the thread_app associated is not being made? Any ideas why?
Thank you
Upvotes: 3
Views: 3175
Reputation: 7803
callings model.save
does not save associations unless you tell it to
you can set autosave
class Form < ActiveRecord::Base
belongs_to :thread_app , :autosave => true
end
or call save on it in the controller
@thread_app.save
or you can take it out of the controller entirely and do this with a callback
class Form < ActiveRecord::Base
before_create :create_thread_app
def create_thread_app
self.thread_app ||= ThreadApp.create(...)
end
end
or after_create, _before_validation_on_create, or any other call back would work
--UPDATE--
this might make a difference using create inse=tead of new, and appables
that you specified as '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
....
Upvotes: 4
Reputation: 27961
Instead of:
@thread_app = @thread.thread_apps.new
You should have:
@thread_app = @thread.thread_apps.create
Upvotes: 2