1
我有这样一个模型:查看Rails中不调用重写属性访问器
class Transaction < ActiveRecord::Base
def amount
self[:amount].abs
end
def transaction_type
read_attribute(:amount) > 0 ? :credit : :debit
end
def transaction_type=(type)
if type == :credit || type == 'credit'
self[:amount] = amount.abs
elsif type == :debit || type == 'debit'
self[:amount] = amount.abs * -1
else
raise ArgumentError.new 'Type must be credit or debit'
end
end
end
因为我希望我的量柱始终是正数渲染时。问题显然是从来没有视为这种方法:
<% form_for @transaction do |f| %>
<%= f.error_messages %>
<p>
<%= f.label 'Where?' %><br />
<%= f.text_field :target %>
</p>
<p>
<%= f.label 'What?' %><br />
<%= f.text_field :memo %>
</p>
<p>
<%= f.label 'How much?' %><br />
<%= f.text_field :amount %>
</p>
<p>
<%= f.radio_button :transaction_type, 'debit' %>
<%= f.label :transaction_type_debit, 'Debit' %>
<%= f.radio_button :transaction_type, 'credit' %>
<%= f.label :transaction_type_credit, 'Credit' %>
</p>
<p><%= f.submit "Submit" %></p>
<% end %>
我做错了什么?还是有更好的方法来做到这一点?
编辑:添加我的transaction_type访问器方法,这更好地解释了为什么我没有在数据库中存储金额作为一个正数。
您能否添加更多信息 - 比如为什么不将它作为正数存储在数据库中,而不是在视图级别进行渲染? – 2009-05-23 00:44:57