Skip to content

Instantly share code, notes, and snippets.

@thechrisoshow
Created July 26, 2012 14:09
Show Gist options
  • Save thechrisoshow/3182245 to your computer and use it in GitHub Desktop.
Save thechrisoshow/3182245 to your computer and use it in GitHub Desktop.
How to best represent a field that uses multiple inputs with activerecord
# The problem I have is that I've got a sort_code field in the database, and I want to keep that as one field
# BUT I want users to edit it in the form using 3 different fields.
# My initial solution was to use virtual attributes and divide it this way.
# Can you think of a better way?
class Account < ActiveRecord::Base
def sort_code_one
sort_code[0..1]
end
def sort_code_one=(value)
sort_code[0] = value[0].to_s
sort_code[1] = value[1].to_s
end
def sort_code_two
sort_code[2..3]
end
def sort_code_two=(value)
sort_code[2] = value[0].to_s
sort_code[3] = value[1].to_s
end
def sort_code_three
sort_code[4..5]
end
def sort_code_three=(value)
sort_code[4] = value[0].to_s
sort_code[5] = value[1].to_s
end
end
# And in the form:
<%= form_for @account do |f| %>
<%= f.label :sort_code %>
<%= f.text_field sort_code_one %>
<%= f.text_field sort_code_two %>
<%= f.text_field sort_code_three %>
<% end %>
@thechrisoshow
Copy link
Author

@h-lame Actually, that's a good point. This code is purely for displaying the sort code, and has no business being in the model. A helper makes more sense

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment