【发布时间】:2017-01-26 04:04:07
【问题描述】:
基本上我想通过 Account (account_id) 来确定资源的范围,所以我在我的 accounts base_controller 中创建了一个名为 current_account 的方法和助手。
我最初使用子域作为唯一标识符,但现在我想放弃使用子域并让每个用户(包括我的帐户所有者用户)通过 account_id 关联。
我遇到的问题是我无法在帐户控制器中找到正确的方法来构建帐户并将 account_id 属性分配给所有者用户。我认为这可能与我同时构建所有者的方式有关。帐户所有者很重要,因为他们有权向帐户添加/邀请新用户。
谁能帮忙?
背景
- 第一个注册的用户成为帐户所有者。
- 然后帐户所有者可以邀请其他用户加入该帐户。
- 我正在使用设计 gem。资源按帐户划分,因此只有与帐户关联的用户才能看到属于该帐户的记录。
帐户模型
class Account < ActiveRecord::Base
belongs_to :owner, class_name: "User"
accepts_nested_attributes_for :owner
validates :subdomain, presence: true, uniqueness: true
has_many :users
has_many :contacts
has_many :invitations
end
用户模型
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :account
end
账户控制人
def new
@account = Account.new
@account.build_owner
end
def create
@user = current_user
@account = @user.account.build_user(account_params)
if @account.save
sign_in(@account.owner)
flash[:notice] = "Your account has been created."
redirect_to dashboard_index_path(current_user)
# redirect_to root_url(subdomain: @account.subdomain)
else
flash.now[:alert] = "Sorry, your account could not be created."
render :new
end
end
架构
create_table "accounts", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "owner_id"
t.string "subdomain"
end
add_index "accounts", ["subdomain"], name: "index_accounts_on_subdomain"
create_table "invitations", force: true do |t|
t.string "email"
t.integer "account_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "token"
end
add_index "invitations", ["account_id"], name: "index_invitations_on_account_id"
add_index "invitations", ["token"], name: "index_invitations_on_token"
create_table "users", force: true do |t|
t.string "email", default: "", null: false
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, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "account_id"
end
add_index "users", ["account_id"], name: "index_users_on_account_id"
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
【问题讨论】:
标签: ruby-on-rails activerecord devise multi-tenant user-accounts