我有三个名为User
,Account
和AccountPermission
的模型。
我在User
和Account
到AccountPermission
之间建立了关联,所以,has_many :through
我还通过 creator_id 与User
建立了Account
和has_many
。因为,我需要知道帐户的创建者。
这是我的协会,
user.rb
class User < ActiveRecord::Base
has_many :created, class_name: 'Account', :foreign_key => 'creator_id'
has_many :account_permissions, :class_name => 'AccountPermission'
has_many :accounts, through: :account_permissions
accepts_nested_attributes_for :account_permissions
account.rb
class Account < ActiveRecord::Base
belongs_to :creator, class_name: 'User'
has_many :accounts_permissions, :class_name => 'AccountPermission'
has_many :users, through: :accounts_permissions
account_permission.rb
class AccountPermission < ApplicationRecord
belongs_to :user
belongs_to :account
accepts_nested_attributes_for :account
控制器#新
def new
@user = User.new
@user.account_permissions.build.build_account
respond_with(@user)
end
我正在使用嵌套属性创建Account
和User
。不过,我还想在同一笔交易中向我的User
添加 creator_id 。
我目前正在向我的用户添加creator_id;
resource.accounts.last.update(creator_id: resource.id)
这是一个非常低级别的解决方案,我感觉不舒服。因为,我每次都会发送一个额外的更新查询。
问题是,有没有办法在帐户创建中处理这个问题?
已更新
def create
build_resource(sign_up_params)
resource.save
yield resource if block_given?
if resource.persisted?
# TODO:
resource.accounts.last.update(creator_id: resource.id)
if resource.active_for_authentication?
set_flash_message! :notice, :signed_up
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
set_minimum_password_length
respond_with resource
end
end
答案 0 :(得分:0)
也许在模型账户中使用回调after_create?
total+= $1 / ($2=="kb" ? 1000: 1)