Skip to content

Instantly share code, notes, and snippets.

@slumos
Created March 28, 2014 20:00
Show Gist options
  • Select an option

  • Save slumos/9841793 to your computer and use it in GitHub Desktop.

Select an option

Save slumos/9841793 to your computer and use it in GitHub Desktop.
Why prefer ActiveRecord `attribute=`
User.create(username: 'jdoe', name: 'John Doe')
User.find_by_name('John Doe')
# create table user (
# id int,
# username varchar(12),
# name varchar(255),
# updated_at timestamp with time zone,
# created_at timestamp with time zone
# )
class User < ActiveRecord::Base
end
# alter table users add column (first_name varchar(255))
# alter table users rename column name last_name
class User < ActiveRecord::Base
def split_name(name)
# TODO something fancy
name.split(/\s+/, 2)
end
def name=(name)
fn, ln = split_name(name)
write_attribute(:first_name, fn)
write_attribute(:last_name, ln)
end
def find_by_name(name)
find_by_first_name_and_last_name(*split_name(name))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment