我有点奇怪的情况(至少我觉得这很奇怪......)
当我在我的应用中创建新帐户时,我还会创建帐户所有者(设计用户)
我遇到问题的地方是我需要将account_id添加到所有者记录中,并将owner_id添加到帐户记录中。然后,所有者可以邀请用户访问其帐户,这些用户需要在其记录中设置account_id。现在,当我尝试创建帐户和所有者时,我得到以下服务器输出和错误:(注意帐户不存在,也不是用户的剂量 - 它是一个干净的数据库..我100%肯定由于我的关系如何建立,这是失败的。
Account
我的class Account < ApplicationRecord
RESTRICTED_SUBDOMAINS = %w(www admin loadlead)
belongs_to :owner, class_name: 'User'
has_many :users
validates :owner, presence: true
validates :subdomain, presence: true,
uniqueness: { case_sensitive: false },
format: { with: /\A[\w\-]+\Z/i, message: 'Contains invalid characters' },
exclusion: { in: RESTRICTED_SUBDOMAINS, message: 'restricted name'}
accepts_nested_attributes_for :owner
before_validation :downcase_subdomain
private
def downcase_subdomain
self.subdomain = subdomain.try(:downcase)
end
end
型号
User
我的class User < ApplicationRecord
enum role: [:system_admin, :owner, :admin, :user]
# Include default devise modules. Others available are:
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :confirmable
validates :f_name, :l_name, :country_code, :phone_number, presence: true
after_initialize :set_default_role, :if => :new_record?
belongs_to :account
private
def set_default_role
self.role ||= :user
end
end
型号
AccountController
我的 def create
@account = Account.new(account_params)
byebug
if @account.valid?
@account.owner.update_attributes(role: 1)
@account.owner.update_attributes(account_id: @account.id)
@aaccount.save
redirect_to root_path, notice: 'Company subdomain created successfully.'
else
render action: 'new', alert: 'There was a problem. Please try again.'
end
end
创建方法:
Started POST "/accounts" for 127.0.0.1 at 2018-04-09 21:21:05 -0600
Processing by AccountsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"pH8vf0MtXpZ/rtyFw8dJ1XKeJ3heR9Mk8deDWWGDgbxrtgrtSuNvpmB2iVIs178z8g1AcSBrumm7DJCwqnoWEg==", "account"=>{"owner_attributes"=>{"f_name"=>"xxxxxx", "m_name"=>"xxxxxx", "l_name"=>"xxxxxx", "country_code"=>"1", "phone_number"=>"xxxxxxxx", "email"=>"xxxxxx@taurenltd.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "subdomain"=>"TaurenGroup"}, "commit"=>"Create Account"}
非常感谢这里的任何帮助。
尝试创建时的服务器输出:
{{1}}
答案 0 :(得分:0)
好的,所以我把这一切都搞定了..它的工作..也许还有更好的方法???
User
型号
belongs_to :account
Account
型号
has_one :owner, class_name: 'User'
has_many :users
这样做使我不必更新或创建create上的关联属性。
感谢您的所有投入!