如何在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屋!