Created
March 28, 2014 20:00
-
-
Save slumos/9841793 to your computer and use it in GitHub Desktop.
Why prefer ActiveRecord `attribute=`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| User.create(username: 'jdoe', name: 'John Doe') | |
| User.find_by_name('John Doe') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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