【发布时间】:2018-04-02 19:06:52
【问题描述】:
在我的应用程序中,我有帐户、用户和权限。创建新用户时,我已经自动创建了一个帐户记录,其中新用户外键设置为帐户表中的“所有者 ID”。在完成此操作的同时,我想在我的 Permissions 表中添加一条记录,在它们各自的列中设置新的 account_id 和新的 user_id,并将资源列设置为“帐户”,并将角色列设置为“所有者” ”。
这是我的模型的外观:
account.rb
class Account < ApplicationRecord
belongs_to :owner, class_name: "User"
has_many :permissions
end
user.rb
class User < ApplicationRecord
...
has_one :account, foreign_key: "owner_id"
has_many :permissions
after_initialize :set_account
...
private
def set_account
build_account unless account.present?
end
end
permissions.rb
class Permission < ApplicationRecord
belongs_to :account
belongs_to :user
end
我希望通过将“set_account”修改为以下内容至少可以填充 Permissions 表的 account_id 和 user_id 列,但我收到“未定义的局部变量或方法 'build_permission' 错误。
def set_account
build_account and build_permission unless account.present?
end
这是我用来显示表/列的架构文件:
ActiveRecord::Schema.define(version: 2018_04_02_040606) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "accounts", force: :cascade do |t|
t.integer "hash_id"
t.integer "owner_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["hash_id"], name: "index_accounts_on_hash_id", unique: true
t.index ["owner_id"], name: "index_accounts_on_owner_id"
end
create_table "permissions", force: :cascade do |t|
t.integer "account_id"
t.integer "user_id"
t.string "resource"
t.string "role"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["account_id", "user_id"], name: "index_permissions_on_account_id_and_user_id", unique: true
end
create_table "users", force: :cascade 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.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.jsonb "settings"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "users"
end
我将不胜感激任何关于我可能遗漏的内容或我从这里到哪里让它按我想要的方式工作的见解。
【问题讨论】:
-
不需要在权限表中添加user_id,可以通过关联获取用户的权限,只需在用户模型中添加
has_many :permissions, through: :account这一行 -
@Vishal 不确定这是否适用于我要进行的设置。每个用户都有自己的帐户,但用户可以授予其他用户对其帐户具有一定访问权限的权限。根据您的建议,如果我通过: :account 分配了用户权限,这不就意味着所有者拥有自己的帐户吗?如果 userB 有 userA 帐户的权限条目,我将如何查找?
标签: ruby-on-rails activerecord