Skip to content

Instantly share code, notes, and snippets.

@faun
Last active August 29, 2015 14:01
Show Gist options
  • Save faun/60a0ce91401006c33222 to your computer and use it in GitHub Desktop.
Save faun/60a0ce91401006c33222 to your computer and use it in GitHub Desktop.
Issue with Rails 4.1 has_many uniq through and order
require 'rubygems'
require 'active_record'
require 'logger'
ActiveRecord::Base.establish_connection(adapter: 'postgresql', host: 'localhost', database: 'test_database')
ActiveRecord::Base.logger = Logger.new(STDOUT)
logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table "authors", force: true do |t|
t.string "name"
t.timestamps
end
create_table "authorships", id: false, force: true do |t|
t.integer "author_id", null: false
t.integer "zine_id", null: false
end
add_index "authorships", ["author_id", "zine_id"], name: "index_authorships_on_author_id_and_zine_id", unique: true, using: :btree
create_table "zines", force: true do |t|
t.string "title", null: false
t.boolean "published", default: true
t.timestamps
end
end
class Author < ActiveRecord::Base
has_many :authorships
has_many :zines, through: :authorships
scope :published, -> {
joins(:zines)
.merge(Zine.published)
.except(:order)
.distinct(Author.arel_table[:id])
.order(name: :desc)
}
end
class Zine < ActiveRecord::Base
has_many :authorships
has_many(:authors,
-> { distinct },
through: :authorships)
scope :published, -> {
where(published: true)
.order(updated_at: :desc)
}
end
class Authorship < ActiveRecord::Base
belongs_to :author,
validate: true,
dependent: :destroy
belongs_to :zine, validate: true
end
zine = Zine.create!(title: "A Guide to Becoming a Superhero", published: true)
author_1 = Author.create!(name: 'Alfred')
Authorship.create(zine_id: zine.id, author_id: author_1.id)
author_2 = Author.create!(name: 'Batman')
Authorship.create(zine_id: zine.id, author_id: author_2.id)
Author.create!(name: 'Robin') # Unpublished author
logger.debug Author.published
source 'https://rubygems.org'
# gem 'activerecord', '4.0.5'
gem 'activerecord', '4.1.1'
gem 'pg'
GEM
remote: https://rubygems.org/
specs:
activemodel (4.1.1)
activesupport (= 4.1.1)
builder (~> 3.1)
activerecord (4.1.1)
activemodel (= 4.1.1)
activesupport (= 4.1.1)
arel (~> 5.0.0)
activesupport (4.1.1)
i18n (~> 0.6, >= 0.6.9)
json (~> 1.7, >= 1.7.7)
minitest (~> 5.1)
thread_safe (~> 0.1)
tzinfo (~> 1.1)
arel (5.0.1.20140414130214)
builder (3.2.2)
i18n (0.6.9)
json (1.8.1)
minitest (5.3.3)
pg (0.17.1)
thread_safe (0.3.3)
tzinfo (1.1.0)
thread_safe (~> 0.1)
PLATFORMS
ruby
DEPENDENCIES
activerecord (= 4.1.1)
pg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment