CaptainCarl
CaptainCarl

Reputation: 3489

has and belongs to many rails 4

When I create a new group in my application I want the logged in user(Devise) to be associated with automatically. More users can be added to the group later on aswell. One user can have many groups. One group can have many users.

How do I associate the logged in user on creation?

My group.rb:

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users
    has_and_belongs_to_many :clients
end

groups_controller.rb (create)

  def create
    @group = Group.new(group_params)
    @group.users.id = current_user.id

    respond_to do |format|
      if @group.save
        format.html { redirect_to @group, notice: 'Group was successfully created.' }
        format.json { render action: 'show', status: :created, location: @group }
      else
        format.html { render action: 'new' }
        format.json { render json: @group.errors, status: :unprocessable_entity }
      end
    end
  end

And group_params from groups_controller.rb

def group_params
      params.require(:group).permit(:name, { :user_ids => [] },)
    end

My schema.rb contains:

  create_table "groups", force: true do |t|
    t.string   "name"
    t.string   "background"
    t.integer  "clocktype"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "groups_users", id: false, force: true do |t|
    t.integer "group_id"
    t.integer "user_id"
  end

  add_index "groups_users", ["group_id"], name: "index_groups_users_on_group_id"
  add_index "groups_users", ["user_id"], name: "index_groups_users_on_user_id"
  create_table "users", force: true do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.string   "email"
    t.string   "password"
    t.string   "avatar"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
  end

Upvotes: 1

Views: 5279

Answers (3)

Nikita Singh
Nikita Singh

Reputation: 370

Try this:-

@group = Group.new(group_params)
@group.users = User.where(:id => current_user.id)
@group.save

Upvotes: 0

tihom
tihom

Reputation: 8003

Following would add the current user to the created group:

# In controller after @group.save
@group.users << current_user

See the association method docs for more info.

Upvotes: 4

okodo
okodo

Reputation: 236

@group.user_ids = [current_user.id]

Upvotes: 1

Related Questions