Skip to content

Instantly share code, notes, and snippets.

@Incanus3
Last active August 29, 2015 13:57
Show Gist options
  • Save Incanus3/9784440 to your computer and use it in GitHub Desktop.
Save Incanus3/9784440 to your computer and use it in GitHub Desktop.
activerecord 4.0.4 when and find_by ignores custom foreign_key when searching for association = nil
#!/usr/bin/env ruby
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
# gem 'rails', github: 'rails/rails'
gem 'rails'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :firma
create_table :jidelak do |t|
t.integer :firma_key
end
end
class Canteen < ActiveRecord::Base
self.table_name = 'firma'
has_many :meals, foreign_key: 'firma_key'
end
class Meal < ActiveRecord::Base
self.table_name = 'jidelak'
belongs_to :canteen, foreign_key: 'firma_key'
end
class BugTest < Minitest::Spec
def setup
@canteen = Canteen.create!
@meal1 = Meal.create!(canteen: @canteen)
@meal2 = Meal.create!()
end
def teardown
Canteen.delete_all
Meal.delete_all
end
def test_finds_records_with_association
assert_equal [@meal1], Meal.where(canteen: @canteen)
assert_equal @meal1, Meal.find_by(canteen: @canteen)
end
def test_finds_records_with_no_association
assert_equal [@meal2], Meal.where(canteen: nil)
assert_equal @meal2, Meal.find_by(canteen: nil)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment