View in Rails doesn't trigger overridden access attribute

I have a model like this:

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

      

Because I want my sum column to always be a positive number when rendering. The problem seems to be that this view never calls this method:

<% 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 %>

      

Am I doing something wrong? Or is there a better way to do this?

Edit: Added transaction accessors of type article_type, which better explains why I didn't store the amount in the DB only as a positive number.

+1


a source to share


1 answer


I had a similar problem a few years ago. Given the timing, excuse me if I'm wrong.

As far as I remember, form helpers use accessor methods *_before_type_cast

. Try renaming your method to amount_before_type_cast

. Below is more information about the "problem" here .



If, however, you ONLY want the number to be absolute in the views, but still want to use the number in the normal way within the model, this is the whole wrong approach and you should instead sanitize your data for use in the view in another way (i.e. (i.e. helper, in the controller, or with all the new custom attributes on the model).

+2


a source







All Articles