当我在我的应用程序中创建一个新组时,我希望登录的用户(设计)自动关联。以后也可以将更多用户添加到组中。一个用户可以有多个组。一个组可以有很多用户。
如何在创建时关联登录用户?
我的组.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