Skip to content

Instantly share code, notes, and snippets.

@eiel
Created March 20, 2013 05:59
Show Gist options
  • Save eiel/5202625 to your computer and use it in GitHub Desktop.
Save eiel/5202625 to your computer and use it in GitHub Desktop.
ActiveRecordを何気なくつかってると気づかないけど、代入時に型変換してくれる。ActiveModel でフォームつかってたときに bool にするにはどうすればいいか悩んだので調べたら ActiveRecord::ConnectionAdapters::Column.value_to_boolean を使えば良さそう。
# $ gem install active_record sqlite3
require 'active_record'
require 'sqlite3'
DATABASE_FILE = File.join(File.dirname(__FILE__), "convert.sqlite")
`rm #{DATABASE_FILE}`
ActiveRecord::Base.establish_connection(
adapter: "sqlite3",
database: DATABASE_FILE,
)
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.integer :age
t.boolean :is_person
t.timestamps
end
end
end
CreateUsers.new.migrate :up
class User < ActiveRecord::Base
end
# ActiveRecord だとだと文字列を渡しても型変換してくれる
# というか普段はフォームから受けとるので文字列がくる
user = User.new(age: '20')
user.age # => 20
user.age.class # => Fixnum
user = User.new(is_person: "1")
user.is_person # => true
user.is_person.class # => TrueClass
# ActiveModel だと自分でやらなきゃならない。
class User2
attr_reader :age, :is_person
include ActiveRecord::ConnectionAdapters
def initialize(attributes = {})
attributes.each do |key, value|
send("#{key}=",value)
end
end
def age=(age)
@age = age.to_i
end
def is_person=(is_person)
@is_person = Column.value_to_boolean(is_person)
end
end
user = User2.new(age: '20')
user.age # => 20
user.age.class # => Fixnum
user = User2.new(is_person: "1")
user.is_person # => true
user.is_person.class # => TrueClass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment