Overriding getter/setter in Rails whilst preserving Model.new({attrib: 'blah'}) format

Viewed 4796

If I override a getter and setter in my model, what's the best way to create default initial values for that attribute in my controller?

For instance, when I create a new instance of the model in the controller to include some initial values, the pre-populated values in the form show the output from the setter rather than the getter.

How should this be done?

Example

class Something < ActiveModel:Base
  # override getter
  def attr_a
    self[:attr_a] * 5 
  end
  # override setter
  def attr_a=
    self[:attr_a] = attr_a / 5 # i.e. 10 / 5 = 2
  end
end

class SomethingController < ActiveController
  def new
    @something = Something.new({attr_a: 10})
  end
end

# index.html.erb
<% form_for @something do |f| %>
  <% f.text_field :attr_a %>
  <% f.submit 'Save' %>
<% end %>

In this example, the text_field in the form is populated with 2 rather than 10.

I can see why it makes sense to by showing 2 as the setting's being called as part of the object instantiation, but am I going about things the wrong way to get the result I want?

Essentially, data needs to be stored in the database in a different way to how it's used in application logic and what the user should see. I want to make that as seamless as possible.

3 Answers
Related