我正在使用Rails(我的Rails技能有點生疏)處理某種項目管理應用程序。我有兩個模型對象,在這種情況下,用戶和賬戶有多對多的關係(公司可能可能是一個更好的帳戶名稱)。當用戶註冊一個新的帳戶時(通過.build)創建一個嵌套表單的幫助。帳戶模型有兩個字段name和account_admin。當初始用戶創建帳戶時,我想將account_admin設置爲用戶標識。但我無法得到這個工作。如何在Rails 3.2中使用.build方法時設置ActiveRecord模型屬性(多對多)
的模型設置如下:
class Account < ActiveRecord::Base
attr_accessible :name, :account_admin
validates_presence_of :name
has_many :projects, dependent: :destroy
has_many :collaborators
has_many :users, through: :collaborators
end
class User < ActiveRecord::Base
has_secure_password
attr_accessible :email, :name, :password, :password_confirmation, :accounts_attributes
has_many :collaborators
has_many :accounts, through: :collaborators
accepts_nested_attributes_for :accounts
[...]
的UserController的是這樣的:
def new
if signed_in?
redirect_to root_path
else
@user = User.new
# Here I'm currently trying to set the account_admin value, but it seems to be nil.
account = @user.accounts.build(:account_admin => @user.id)
end
end
我也試圖移動到創建行動,但該領域的消失表格。
什麼是適當的方式來實現我想要的(在創建時將account_admin設置爲用戶ID)?或者是否有更好的方法來找出哪個用戶創建了賬戶(即對關係表進行一些操作)?
更新
與@joelparkerhenderson的幫助,我想我得到它的工作。
def set_account_admin
account = self.accounts.last
if account.account_admin == nil
account.account_admin = self.id
account.save
end
end
我與after_create :set_account_admin
打電話:我在用戶模式,看起來像這樣做的方法。這有效,但是還有更多的「Rails方法」來做同樣的事情嗎?
謝謝。
謝謝,這似乎工作。我做了一個看起來像這樣的方法,我在用戶模型中用'after_create'調用。 '高清set_account_admin 帳戶= self.accounts.last 如果account.account_admin ==零 account.account_admin = self.id account.save 結束 end'這是做了正確的方法是什麼? – Anders 2012-04-07 12:17:11
是的,那很好。 Rails 3可能有更好的方法來做到這一點 - 這可能是一個好主意,讓你的問題保持開放,看看其他人是否有想法。 – joelparkerhenderson 2012-04-07 12:33:39
謝謝,幾天後會給你正確的答案,除非其他人有更多的「可選」解決方案。 :) – Anders 2012-04-07 13:44:32