首页 文章

有很多通过与控制台的工作联系而不是从控制器 .

提问于
浏览
0

我通过关联有一个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)commit transaction =>#

但是当我尝试通过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开始POST“/ groups”for 127.0.0.1由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)begin transaction SQL(0.8ms)INSERT INTO“groups”(“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“,Tue,2013年10月1日08:20:15 UTC 00:00]](6.1 ms)提交事务

这只会创建一个新的组记录,而不是连接表中的记录 . 我无法理解是什么造成了这种差异 .

2 回答

  • 0

    lol007是对的,或者你也可以这样做

    在新的行动

    @group = current_user.groups.build
    

    并在创造行动

    @group = current_user.groups.create(params[:group])
    
  • 0

    您需要使用 build 方法:

    current_user.groups.build(params[:group])
    

相关问题