[英]Managing users in Ruby on Rails (& ownership)
我有點像Rails的新手,並且不太確定將用戶綁定到他們的對象(例如文檔)時的約定。 (我現在知道在Rails中使用約定是多么重要)
到目前為止,我已經想出了3個可能的解決方案:
has_many
和belongs_to
使每個文檔基本上成為每個用戶的子文檔 user_id
,或類似的東西),將其與用戶聯系起來。 這樣,只要用戶想要他們的文檔索引,我就可以識別所有具有正確ID的索引。 此外,我計划使用Devise進行用戶身份驗證和管理。 根據我的理解,這似乎是最受歡迎/廣泛使用的認證寶石 - 如果我錯了,請糾正我。
這主要是一個基於意見的問題,但我傾向於看到大多數項目使用ActiveRecord的關系(例如has_many
, belongs_to
)。
你可以使用devise進行身份驗證(或構建一個自己的登錄系統, 有一個railscast並使用cancancan進行授權。你可以在文檔中找到一些能力定義,例如
can :update, Article
或者如果用戶可以刪除自己的東西
can :read, Project, active: true, user_id: user.id
我還將使用與has_many
eg和has_many through
的ActiveRecord關系
我有點像Rails的新手
歡迎來到俱樂部,雖然有些人咬人,但大部分都很酷。
將用戶綁定到他們的對象
你已經回答了自己的問題 ......
#app/models/user.rb
class User < ActiveRecord::Base
has_many :documents
end
#app/models/document.rb
class Document < ActiveRecord::Base
belongs_to :user
end
如果用戶創建文檔,那肯定意味着您必須通過has_many
/ belongs_to
關系將documents
關聯到users
...
-
為了給你一些上下文,你必須將user_id
foreign_key添加到你的documents
表:
$ rails g migration AddUserForeignKeyToDocuments
#db/migrate/add_user_foreign_key_to_documents______.rb
class AddUserForeignKeyToDocuments < ActiveRecord::Migration
def change
change_table :documents do |t|
t.references :user, index: true
end
end
end
$ rake db:migrate
這將允許類似下面的內容(使用Devise
的current_user
幫助程序 ):
#config/routes.rb
resources :documents
#app/controllers/documents_controller
class DocumentsController < ApplicationController
def create
@document = current_user.documents.new document_params
@document.save
end
private
def document_params
params.require(:document).permit(.....)
end
end
如果您不確定用戶身份驗證,您應該使用Devise
,盡管還有其他身份驗證寶石,例如sorcery
設置Devise
很簡單:
#Gemfile
gem 'devise', '~> 3.5', '>= 3.5.3'
$ rails generate devise:install
$ rails generate devise User
$ rake db:migrate
#config/routes
devise_for :users
#app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
before_action :authenticate_user!
end
這將使它只有登錄用戶可以訪問/documents
:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.