How to save many has_many_through objects at the

2019-02-15 09:12发布

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?

2条回答
干净又极端
2楼-- · 2019-02-15 09:29

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

查看更多
Summer. ? 凉城
3楼-- · 2019-02-15 09:38

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

查看更多
登录 后发表回答