0
votes

I have a problem with a has_many through association. Somehow u.groups.create!(:name => "test group", :school => "the school") makes a correct insert with the trace:

(0.1ms) begin transaction 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", Tue, 01 Oct 2013 08:13:36 UTC +00:00], ["group_id", 7], ["updated_at", Tue, 01 Oct 2013 08:13:36 UTC +00:00], ["user_id", 1]] (0.5ms) commit transaction => #

But when I try via the 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

This creates the trace:

Started POST "/groups" for 127.0.0.1 at 2013-10-01 10:20:15 +0200 Processing by GroupsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"frETQoB5Mu2gLnIBG644i09XDOHFsEBTGEvrEQmfgPA=", "group"=>{"name"=>"Test group2", "school"=>"Another school", "findeble"=>"1"}, "commit"=>"Create Group"} User Load (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", Tue, 01 Oct 2013 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) commit transaction

This only creates a new group record and not a record in the joined table. I cant understand what makes this difference.

2

2 Answers

0
votes

You need to use build method:

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

lol007 is right or you can also do it like that

In new action

  @group = current_user.groups.build

And in create action

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