Skip to content

Instantly share code, notes, and snippets.

@wkrsz
Created March 3, 2013 15:39
Show Gist options
  • Save wkrsz/5076568 to your computer and use it in GitHub Desktop.
Save wkrsz/5076568 to your computer and use it in GitHub Desktop.
add with_association_target to ActiveRecord Relation class
ActiveRecord::Relation.class_eval do
def with_association_target(targets)
@association_target = (@association_target||{}).merge(targets)
self
end
def load_with_association_targets(*args)
load_without_association_targets(*args).tap do
@records.each{|record| set_association_targets(record) }
end
end
alias_method_chain :load, :association_targets
private
def set_association_targets(record)
if @association_target.present?
@association_target.each do |association_name, target|
record.association(association_name).target = target
end
end
end
end
require 'test_helper'
class WithAssociationTargetTest < ActiveSupport::TestCase
fixtures :all
def setup
@hermine_ramon = clients(:hermine_ramon)
@new_client = clients(:new_client)
@association = @hermine_ramon.tasks
end
test "association with scope" do
assert_equal @new_client, @association.order('id').with_association_target(client: @new_client)[0].client
end
test "first" do
assert_equal @new_client, @association.order('created_at').with_association_target(client: @new_client).first.client
end
test "multiple" do
new_task_template = TaskTemplate.new
subject = @association.order('id') \
.with_association_target(client: @new_client, task_template: new_task_template)
assert_equal @new_client, subject[0].client
assert_equal new_task_template, subject[0].task_template
end
test "chains" do
new_task_template = TaskTemplate.new
subject = @association.order('id') \
.with_association_target(client: @new_client) \
.with_association_target(task_template: new_task_template)
assert_equal @new_client, subject[0].client
assert_equal new_task_template, subject[0].task_template
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment