Permalink
Browse files

- Active Resrource associations, has one should return the associated…

… resource
  • Loading branch information...
1 parent 1cbff55 commit e440e23488f95d22d4c9e3039f1bd177c6c1d648 @gramos committed Sep 27, 2010
@@ -4,7 +4,11 @@ module Associations
def hash_options(association, resource)
h = { :klass => klass_for(association, resource) }
h[:host_klass] = self
- h[:association_col] = "#{h[:host_klass].to_s.downcase}_id".to_sym
+ if association == :has_many
+ h[:association_col] = "#{h[:host_klass].to_s.downcase}_id".to_sym
+ else
+ h[:association_col] = "#{h[:klass].to_s.underscore}_id".to_sym
+ end
h
end
@@ -23,9 +27,11 @@ def has_one(resource, opts = {})
#
#----------------------------------------------------------------------#
define_method(klass_name) do
+ resource_id = send(h[:association_col])
+
if instance_variable_get("@#{resource}").nil?
instance_variable_set("@#{resource}",
- h[:klass].find(:params => { h[:association_col] => id }) )
+ h[:klass].find(resource_id) )
end
return instance_variable_get("@#{resource}")
end
@@ -2,20 +2,49 @@
require "fixtures/project"
class ProjectManager < ActiveResource::Base
+ self.site = "http://37s.sunrise.i:3000"
end
class Project < ActiveResource::Base
+ self.site = "http://37s.sunrise.i:3000"
has_one :project_manager
end
+@project = <<-eof.strip
+ <?xml version=\"1.0\" encoding=\"UTF-8\"?>
+ <project>
+ <id type=\"integer\">1</id>
+ <name>Rails</name>
+ <project_manager_id>5</project_manager_id>
+ </project>
+eof
+
+@project_manager = <<-eof.strip
+ <?xml version=\"1.0\" encoding=\"UTF-8\"?>
+ <project_manager>
+ <id type=\"integer\">5</id>
+ <name>David</name>
+ </project_manager>
+eof
+
+ActiveResource::HttpMock.respond_to do |mock|
+ mock.get "/projects/1.xml", {}, @project
+ mock.get "/project_managers/5.xml", {}, @project_manager
+end
+
class AssociationsTest < Test::Unit::TestCase
def setup
- @project = Project.new
+ @project = Project.find(1)
+ @project_manager = ProjectManager.find(5)
end
def test_has_one_should_add_a_resource_accessor
assert @project.respond_to? :project_manager
+
+ # should return the associated project_manager
+ assert_equal @project_manager, @project.project_manager
end
+
end

0 comments on commit e440e23

Please sign in to comment.