如何在Rails中同时保存多个has_many_through对象?

che*_*ell 4 ruby-on-rails save has-many-through

我有两个相关的模型如下。

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
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我想从表单数据创建对象。我这样做如下:

  @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
Run Code Online (Sandbox Code Playgroud)

由于模型是由多个模型连接起来的,有没有一种方法可以一次性保存它们,然后一次生成错误消息,以便它们同时显示在表单上?

rub*_*nce 5

这会做

@user = User.new(params[:user])
@user.boards << @board
@user.save
Run Code Online (Sandbox Code Playgroud)

这将保存与同一命令关联的用户对象和板对象@user.save。它也会创建中间庆祝记录并user_id保存board_id,但在您的情况下,它可能没有用,因为您需要设置庆祝表其他列的值