如何在 Rails 中同时保存多个 has_many_through 对象? [英] 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?
推荐答案
这样就可以了
@user = User.new(params[:user])
@user.boards << @board
@user.save
这将保存用户对象和与同一命令 @user.save
关联的板对象.它还将创建中间庆祝记录并保存 user_id
和 board_id
但在您的情况下,它可能没有用,因为您需要设置庆祝表的其他列的值
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
这篇关于如何在 Rails 中同时保存多个 has_many_through 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!