我有一个帐户模型,我希望balance
只能读取,但可以通过私有方法更新。
目前
class Account < ActiveRecord::Base
def deposit(amount)
# do some stuff and then
update_balance(amount)
end
private
def update_balance(amount)
self.balance += amount
end
end
然而,这仍然是可能的:
account = Account.first
account.balance += 5
account.save
我想上面的错误,但仍然能够做到:
account.balance #=> 0
account.deposit(5)
account.balance #=> 5
答案 0 :(得分:2)
您可以为属性定义私人设定器:
Account
然后,您不能在Account.new(balance: 1234)
# => ActiveRecord::UnknownAttributeError: unknown attribute 'balance' for 'Account'
Account.new.balance = 1234
# => NoMethodError: private method `balance=' called for <Account ...>
课程之外致电:
MainPage_List_Text
答案 1 :(得分:0)
ActiveRecord
不仅仅是rails gem。这是一个常用的pattern,表示对象中数据库的镜像表示。因此,模型中的所有数据访问方法都可以使用ruby元编程机制自动定义。
也许最好保持逻辑清晰,方便,并编写可在AccountManager
之上工作的课程Account
,并为您提供所需的隔离:
class AccountManager
def initialize(account)
@account = account
end
def deposit(amount)
# do some stuff and then
update_balance(amount)
end
private
def update_balance(amount)
@account.balance += amount
end
end