Skip to content

Instantly share code, notes, and snippets.

@yhirano55
Created December 17, 2019 13:27
Show Gist options
  • Save yhirano55/b1e5cb51526d9cdf1ac49d6757c31bf7 to your computer and use it in GitHub Desktop.
Save yhirano55/b1e5cb51526d9cdf1ac49d6757c31bf7 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "rails", github: "rails/rails"
gem "sqlite3"
end
require "rails"
require "active_record/railtie"
require "minitest/autorun"
ENV["DATABASE_URL"] ||= "sqlite3::memory:"
module PluckForKashimaApp
class Application < Rails::Application
config.api_only = true
config.cache_classes = false
config.eager_load = false
config.consider_all_requests_local = true
config.time_zone = 'Tokyo'
config.active_record.default_timezone = :local
secrets.secret_key_base = SecureRandom.uuid
end
end
PluckForKashimaApp::Application.initialize!
class CreateAllTables < ActiveRecord::Migration[6.1]
def self.up
create_table :users, force: true do |t|
t.timestamps
end
create_table :items, force: true do |t|
t.timestamps
end
create_table :user_items, force: true do |t|
t.references :user
t.references :item
t.datetime :used_at
t.boolean :flag, default: false
t.timestamps
end
end
end
class User < ActiveRecord::Base
has_many :user_items
end
class ExtendUser < ActiveRecord::Base
self.table_name = :users
has_many :user_items, foreign_key: :user_id
attribute :used_at, :datetime
attribute :flag, :boolean
end
class Item < ActiveRecord::Base
has_many :user_items
end
class UserItem < ActiveRecord::Base
belongs_to :user
belongs_to :item
end
class BugTest < Minitest::Test
def setup
CreateAllTables.migrate(:up)
end
def test_case
user = User.create!
item = Item.create!
now = Time.current
user_item = UserItem.create!(user: user, item: item, used_at: now)
# 直接pickするとActiveSupport::TimeWithZone
assert_equal now, UserItem.pick(:used_at)
assert_equal ActiveSupport::TimeWithZone, UserItem.pick(:used_at).class
# JoinしてpickするとString
assert_equal String, User.joins(:user_items).pick(:used_at).class
# JoinしてpickするとInteger (本当はboolean)
assert_equal Integer, User.joins(:user_items).pick(:flag).class
# attributeを宣言してJoinしてpickするとString
assert_equal now, ExtendUser.joins(:user_items).pick(:used_at)
assert_equal ActiveSupport::TimeWithZone, ExtendUser.joins(:user_items).pick(:used_at).class
# attributeを宣言してJoinしてpickするとBooleanに
assert_equal FalseClass, ExtendUser.joins(:user_items).pick(:flag).class
# 参考: https://github.com/rails/rails/issues/35232
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment