I have two models related as follows.
USERS
has_many :celebrations
has_many :boards, :through => :celebrations
BOARDS
has_many :celebrations
has_many :users, :through => :celebrations
CELEBRATIONS
:belongs_to :user
:belongs_to :board
In my controller I want to create the objects from form data. I do this as follows:
@user = User.new(params[:user])
@board = Board.new(params[:board])
if @user.save & @board.save
@user.celebrations.create(:board_id => @board,:role => "MANAGER")
redirect_to :action => some_action
end
Since the models are joined by the many through is there a way to save them in one time and then produce the error messages at one time so that they show on the form at the same time?
Your method looks pretty standard to me. To answer your question...
When working with an association, the
<<
operator is basically the same as thecreate
method except:<<
uses a transaction.create
does not.<<
triggers the :before_add and :after_add callbacks.create
does not.<<
returns the association proxy (essentially the collection of objects) if successful, false is not successful.create
returns the new instance that was created.Using the
<<
operator in your case wouldn't get you much since you would still have multiple transactions. If you wanted all of the database inserts/updates in your action to be atomic you could wrap the action into a transaction. See the Rails API for details: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.htmlThis will do
This will save the user object and the board objects associated with the same command
@user.save
. It will create the intermediate celebrations record also with theuser_id
andboard_id
saved but in your case it might not be useful as you need to set values of other columns of celebrations table