0

関連付けによる has_many に問題があります。どういうわけか 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", Tue, 01 Oct 2013 08:13:36 UTC +00:00], ["findeble", false], ["name", "test group"], ["school", "the school" ], ["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", 2013 年 10 月 1 日 08:13:36 UTC +00:00], ["group_id", 7], ["updated_at", 火, 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-01 10:20:15 +0200 で 127.0.0.1 の POST "/groups" を開始しました。 ", "group"=>{"name"=>"Test group2", "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" , "名前", "学校", "updated_at") 値 (?, ?, ?, ?, ?) [["created_at", Tue, 01 Oct 2013 08:20:15 UTC +00:00], ["findeble", true], ["name", "Test group2"], ["school", "別の学校"], ["updated_at", Tue, 01 Oct 2013 08:20:15 UTC +00:00]]
(6.1ms) commit トランザクション

これにより、新しいグループ レコードが作成されるだけで、結合されたテーブル内のレコードは作成されません。この違いが何なのか理解できません。

4

2 に答える 2

0

lol007が正しいか、そのようにすることもできます

新しいアクションで

  @group = current_user.groups.build

そして create アクションで

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

メソッドを使用する必要がありますbuild

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