Created
June 11, 2012 18:44
-
-
Save tuzz/2911869 to your computer and use it in GitHub Desktop.
Associations on collections - ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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