我有一个关于has_many的问题。 不知何故u.groups.create!(:name =>“test group”,:school =>“school”)使用跟踪进行正确插入:
(0.1ms)开始事务SQL(4.5ms)INSERT INTO“groups” (“created_at”,“findeble”,“name”,“school”,“updated_at”)VALUES(?, ?,?,?,?)[[“created_at”,星期二,2013年10月1日08:13:36 UTC +00:00], [“findeble”,false],[“名称”,“测试组”],[“学校”,“学校”], [“updated_at”,星期二,2013年10月1日08:13:36 UTC +00:00]] SQL(0.3ms) INSERT INTO“usergroups”(“created_at”,“group_id”,“updated_at”, “user_id”)VALUES(?,?,?,?)[[“created_at”,星期二,2013年10月1日 08:13:36 UTC +00:00],[“group_id”,7],[“updated_at”,星期二,2013年10月1日 08:13:36 UTC +00:00],[“user_id”,1]](0.5ms)提交事务 => #
但是当我尝试通过groups_controller
时 # GET /groups/new
# GET /groups/new.json
def new
@group = current_user.groups.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @group }
end
end
def create
@group = current_user.groups.new(params[:group])
respond_to do |format|
if @group.save
format.html { redirect_to @group, notice: 'Group was successfully created.' }
format.json { render json: @group, status: :created, location: @group }
else
format.html { render action: "new" }
format.json { render json: @group.errors, status: :unprocessable_entity }
end
end
end
这会创建跟踪:
在2013-10-01 10:20:15 +0200开始为127.0.0.1发布“/ groups” 由GroupsController处理#create as HTML参数: { “UTF8”=> “中✓”, “authenticity_token”=> “中frETQoB5Mu2gLnIBG644i09XDOHFsEBTGEvrEQmfgPA =”, “group”=> {“name”=>“Test group2”,“school”=>“另一所学校”, “findeble”=>“1”},“commit”=>“创建组”}用户负载(0.2ms) SELECT“users”。* FROM“users”WHERE“users”。“id”= 1 LIMIT 1
(0.1ms)开始事务SQL(0.8ms)INSERT INTO“组” (“created_at”,“findeble”,“name”,“school”,“updated_at”)VALUES(?, ?,?,?,?)[[“created_at”,星期二,2013年10月1日08:20:15 UTC +00:00], [“findeble”,true],[“name”,“Test group2”],[“school”,“Another school“],[”updated_at“,星期二,2013年10月1日08:20:15 UTC +00:00]]
(6.1ms)提交事务
这只会创建一个新的组记录,而不是连接表中的记录。我无法理解是什么造成了这种差异。
答案 0 :(得分:0)
您需要使用build
方法:
current_user.groups.build(params[:group])
答案 1 :(得分:0)
lol007是对的,或者你也可以这样做
采取新行动
@group = current_user.groups.build
并在创建动作
@group = current_user.groups.create(params[:group])