我有以下新的和创建的动作。它们用于在多租户应用程序中创建新帐户。它工作正常,但即使是新手,我也知道这是不正确的。这是我的问题,我怎样才能使创建操作更精简,以便遵循最佳实践?而且,我怎样才能使所有查询在一笔交易下提交?
这是我的方法:
def new
@account = Account.new
@user = @account.users.build()
@account.accounts_users.build()
respond_to do |format|
format.html # new.html.erb
format.json { render json: @account }
end
end
def create
@account = Account.new(params[:account])
respond_to do |format|
if @account.save
@user = User.find_by_email(params[:account][:users_attributes]["0"][:email])
Profile.create(:user_id => @user.id)
@group = @account.groups.create(:name => 'Default', :user_id => @user)
@group.members.create(:account_id => @account, :user_id => @user)
Role.all.each do |role|
@user.roles_users.create(:role_id => role.id, :account_id => @account)
end
flash[:domain] = @account.subdomain
format.html { redirect_to thanks_url }
format.json { render json: @account, status: :created, location: @account }
else
format.html { render action: "new" }
format.json { render json: @account.errors, status: :unprocessable_entity }
end
end
end
我的模型是:
- 帐户(has_many :users; :through account_users)
- 用户(has_one :profile)
- Accounts_User(belongs_to :account;belongs_to :user)
- 组(has_many:members,as:membership;belongs_to:user)
- 成员(belongs_to :membership, :polymorphic => true)
- 个人资料(belongs_to :user)
- 角色(has_many :roles_users; has_many :users :through => :roles_users; has_many :accounts, :through => :roles_users)
- RolesUser(belongs_to :user;belongs_to :account;belongs_to :role)