0

我对 has_many through 关联有疑问。不知何故 u.groups.create!(:name => "test group", :school => "the 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”,假],[“名称”,“测试组”],[“学校”,“学校” ], ["updated_at", Tue, 01 Oct 2013 08:13:36 UTC +00:00]] SQL (0.3ms) INSERT INTO "usergroups" ("created_at", "group_id", "updated_at", "user_id" ) VALUES (?, ?, ?, ?) [["created_at", Tue, 01 Oct 2013 08:13:36 UTC +00:00], ["group_id", 7], ["updated_at", Tue, 01 2013 年 10 月 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 月 1 日 10:20:15 +0200 开始 POST "/groups" for 127.0.0.1 由 GroupsController#create 作为 HTML 参数处理:{"utf8"=>"✓", "authenticity_token"=>"frETQoB5Mu2gLnIBG644i09XDOHFsEBTGEvrEQmfgPA= ", "group"=>{"name"=>"Test group2", "school"=>"Another school", "findeble"=>"1"}, "commit"=>"Create Group"} 用户负载(0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
(0.1ms) 开始事务 SQL (0.8ms) INSERT INTO "groups" ("created_at", "findeble" , "name", "school", "updated_at") 值 (?, ?, ?, ?, ?) [["created_at", 2013 年 10 月 1 日星期二 08:20:15 UTC +00:00], ["findeble", true], ["name", "Test group2"], ["school", "Another school"], ["updated_at", Tue, 01 Oct 2013 08:20:15 UTC +00:00]]
(6.1ms) 提交事务

这只会创建一个新的组记录,而不是连接表中的记录。我不明白是什么造成了这种差异。

4

2 回答 2

0

您需要使用build方法:

current_user.groups.build(params[:group])
于 2013-10-01T08:28:03.117 回答
0

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

在新动作中

  @group = current_user.groups.build

在创造行动中

  @group = current_user.groups.create(params[:group])
于 2013-10-01T10:14:35.990 回答