Skip to content

Instantly share code, notes, and snippets.

@shekibobo
Last active September 20, 2018 08:36
Show Gist options
  • Select an option

  • Save shekibobo/6729255 to your computer and use it in GitHub Desktop.

Select an option

Save shekibobo/6729255 to your computer and use it in GitHub Desktop.

Revisions

  1. shekibobo revised this gist Sep 27, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion has_many_through_with_includes_test.rb
    Original file line number Diff line number Diff line change
    @@ -38,7 +38,7 @@ class Group < ActiveRecord::Base
    has_many :users, -> { uniq }, through: :events
    end

    class Events < ActiveRecord::Base
    class Event < ActiveRecord::Base
    belongs_to :group
    belongs_to :user
    end
  2. shekibobo created this gist Sep 27, 2013.
    63 changes: 63 additions & 0 deletions has_many_through_with_includes_test.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    unless File.exists?('Gemfile')
    File.write('Gemfile', <<-GEMFILE)
    source 'https://rubygems.org'
    gem 'rails', github: 'rails/rails'
    gem 'sqlite3'
    GEMFILE

    system 'bundle'
    end

    require 'bundler'
    Bundler.setup(:default)

    require 'active_record'
    require 'minitest/autorun'
    require 'logger'

    # This connection will do for database-independent bug reports.
    ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
    ActiveRecord::Base.logger = Logger.new(STDOUT)

    ActiveRecord::Schema.define do
    create_table :groups do |t|
    end

    create_table :events do |t|
    t.references :group
    t.references :user
    t.datetime :starts_at
    end

    create_table :users do |t|
    end
    end

    class Group < ActiveRecord::Base
    has_many :events, -> { includes(:user) }
    has_many :users, -> { uniq }, through: :events
    end

    class Events < ActiveRecord::Base
    belongs_to :group
    belongs_to :user
    end

    class User < ActiveRecord::Base
    has_many :events, -> { includes(:group) }
    has_many :groups, through: :events
    end

    class BugTest < Minitest::Test
    def test_association_stuff
    group = Group.create!
    user = User.create!
    group.events << Event.create!(starts_at: DateTime.current, user_id: user.id)

    assert_equal 1, group.users.count
    assert_equal 1, Event.count
    assert_equal group.id, Event.first.group.id
    assert_equal 1, user.groups.count
    assert_equal user.id, Event.first.user.id
    end
    end