1

当我在我的应用程序中创建一个新组时,我希望登录的用户(设计)自动关联。以后也可以将更多用户添加到组中。一个用户可以有多个组。一个组可以有很多用户。

如何在创建时关联登录用户?

我的组.rb:

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

groups_controller.rb(创建)

  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

以及来自 groups_controller.rb 的 group_params

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

我的 schema.rb 包含:

  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
4

3 回答 3

4

以下会将当前用户添加到创建的组中:

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

有关更多信息,请参阅关联方法文档

于 2013-10-08T07:00:25.150 回答
1

@group.user_ids = [current_user.id]

于 2013-10-08T06:53:36.247 回答
0

尝试这个:-

@group = Group.new(group_params)
@group.users = User.where(:id => current_user.id)
@group.save
于 2013-10-08T07:01:45.070 回答