问题
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?
回答1:
This will do
@user = User.new(params[:user])
@user.boards << @board
@user.save
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 the user_id
and board_id
saved but in your case it might not be useful as you need to set values of other columns of celebrations table
回答2:
Your method looks pretty standard to me. To answer your question...
When working with an association, the <<
operator is basically the same as the create
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.html
来源:https://stackoverflow.com/questions/5218994/how-to-save-many-has-many-through-objects-at-the-same-time-in-rails