Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save many has_many_through objects at the same time in Rails?

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?

like image 971
chell Avatar asked Oct 12 '25 15:10

chell


2 Answers

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

like image 123
rubyprince Avatar answered Oct 14 '25 14:10

rubyprince


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

like image 39
MDaubs Avatar answered Oct 14 '25 15:10

MDaubs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!