Skip to content

Instantly share code, notes, and snippets.

@tuzz
Created June 11, 2012 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuzz/2911869 to your computer and use it in GitHub Desktop.
Save tuzz/2911869 to your computer and use it in GitHub Desktop.
Associations on collections - ActiveRecord
# Currently, you have to roll your own associations if you want to chain scopes through collections.
# I'm interested to see if there is an existing (generalised) way to do this with AR.
# If not, feedback on the value and interface (method chaining?) for collection associations would be appreciated.
# gem install activerecord
# gem install sqlite3
require 'active_record'
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table :posts do |table|
end
create_table :comments do |table|
table.column :post_id, :integer
end
end
class Post < ActiveRecord::Base
has_many :comments
def self.comments
Comment.where(:post_id => scoped.pluck(primary_key).uniq)
end
end
class Comment < ActiveRecord::Base
belongs_to :post
def self.posts
Post.where(:id => scoped.pluck(:post_id).uniq)
end
end
post = Post.create!
10.times { post.comments.create! }
puts Post.limit(10).comments.posts.comments.posts.to_sql
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment