拥有并属于许多铁轨4

时间:2013-10-08 06:42:32

标签: ruby-on-rails associations ruby-on-rails-4 has-and-belongs-to-many

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

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

我的group.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

3 个答案:

答案 0 :(得分:4)

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

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

有关详细信息,请参阅关联方法docs

答案 1 :(得分:1)

@ group.user_ids = [current_user.id]

答案 2 :(得分:0)

试试这个: -

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