2009-05-23 43 views
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访问器方法,这更好地解释了为什么我没有在数据库中存储金额作为一个正数。

+1

您能否添加更多信息 - 比如为什么不将它作为正数存储在数据库中,而不是在视图级别进行渲染? – 2009-05-23 00:44:57

回答

2

几年前,我有类似的问题。考虑到所涉及的时间,如果我错了,请原谅我。

据我记得,表单助手使用*_before_type_cast访问器方法。考虑将您的方法重命名为amount_before_type_cast。有关于“问题”here的更多信息。

但是,如果您只希望在视图中将数字设为绝对值,但仍然希望在模型中以通常方式使用数字,则完全是错误的方法,您应该“消毒”您的在视图中以不同方式使用的数据(例如,助手,控制器中或模型上全新的非数据库定制属性)。