【问题标题】:has and belongs to many rails 4拥有并属于许多轨道 4
【发布时间】:2013-10-08 06:42:32
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    更多信息请参见关联方法docs

    【讨论】:

    • 就像一个魅力。谢谢!
    【解决方案2】:

    @group.user_ids = [current_user.id]

    【讨论】:

    • 你的回答是对的。不过,蒂尔霍姆的回答似乎不那么灵活。不过还是谢谢!
    【解决方案3】:

    试试这个:-

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

    【讨论】:

      猜你喜欢
      • 2017-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 2017-08-22
      相关资源
      最近更新 更多