我已经设置了必要的模型和视图,以获得Devise资源,帐户和用户。帐户has_many用户&用户belongs_to帐户。该模式将account_id反映为用户的属性。我可能错了,但我的印象是当帐户登录时会自动填写此account_id属性&创建一个新用户。检查Rails控制台后,似乎所有以这种方式创建的新用户都有account_id的nil值。单独的问题,但这是使用Devise在应用程序中实现多租户的理想方式吗?
型号:
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :account, :inverse_of => :users
accepts_nested_attributes_for :account
end
account.rb
class Account < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :users, :inverse_of => :account, :dependent => :destroy
accepts_nested_attributes_for :users
has_many :projects
end
schema.rb(只是用户和帐户)
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"
t.boolean "supervisor"
t.string "name"
end
create_table "accounts", 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.string "name"
end
users_controller.rb
class UsersController < ApplicationController
before_filter :authenticate_user!
def new
@user = User.new
end
def create
@user.skip_confirmation! # confirm immediately--don't require email confirmation
if @user.save
flash[:success] = "User added and activated."
redirect_to users_path # list of all users
else
render 'new'
end
end
def index
@users = User.all
end
end
accounts_controller.rb
class AccountsController < ApplicationController
def new
@accounts = Account.new
@accounts.users.build
end
def create
@account = Account.new(params[:account])
if @account.save
flash[:success] = "Account created"
redirect_to accounts_path
else
render 'new'
end
end
end
来自注册&gt; edit.html.erb
<% if account_signed_in? %>
<div class="jumbotron">
<span><%= link_to "Add user", new_user_registration_path, class: "btn btn-primary btn-sm" %></span>
</div>
<% end %>
答案 0 :(得分:1)
我不确定您是如何创建用户的
但是用
创建用户@account.users.build
会自动将account_id添加到用户对象。
希望这有帮助! :)