Skip to content

Instantly share code, notes, and snippets.

@thechrisoshow
Created July 26, 2012 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 %>
@jgwhite
Copy link

jgwhite commented Jul 26, 2012

Rails’ multiparameter attribute assignment should take care of this (or at least it’s a convention to follow):
https://github.com/rails/rails/blob/d90b4e2/activerecord/lib/active_record/base.rb#L1811

@h-lame
Copy link

h-lame commented Jul 26, 2012

I was going to fork this and do something where you have a sort_code_parts method that takes a hash, but I realised building the form wouldn't be as easy as f.text_field. I suppose it's about where you want to have the messy code, in the model as you have, or in a helper as I would.

@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