Permalink
Browse files

- Active Resource has_one association

  test_should_assign_a_new_project_manager
  • Loading branch information...
1 parent b8c08a9 commit af103773084f54e730b6bbbbe7ecbb3814e008db @gramos committed Sep 28, 2010
View
14 activeresource/lib/active_resource/associations.rb
@@ -36,6 +36,20 @@ def has_one(resource, opts = {})
end
return instance_variable_get("@#{resource}")
end
+
+ #----------------------------------------------------------------------#
+ # Define writter method for resource
+ #
+ #----------------------------------------------------------------------#
+ define_method("#{klass_name}=") do |new_resource|
+ if send(resource).blank?
+ new_resource.send("#{h[:association_col]}=", id)
+ new_resource.save
+ instance_variable_set("@#{resource}", new_resource)
+ else
+ instance_variable_get("@#{resource}").send(:update_attribute, h[:association_col], id)
+ end
+ end
end
end
View
11 activeresource/test/cases/associations_test.rb
@@ -13,22 +13,26 @@ class Project < ActiveResource::Base
@project = { :id => 1, :name => "Rails"}
@other_project = { :id => 2, :name => "Ruby"}
@project_manager = {:id => 5, :name => "David", :project_id =>1}
+@other_project_manager = {:id => 6, :name => "John", :project_id => nil}
@project_managers = [@project_manager]
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/projects/1.xml", {}, @project.to_xml(:root => 'project')
mock.get "/projects/2.xml", {}, @other_project.to_xml(:root => 'project')
mock.get "/project_managers/5.xml", {}, @project_manager.to_xml(:root => 'project_manager')
+ mock.get "/project_managers/6.xml", {}, @other_project_manager.to_xml(:root => 'project_manager')
mock.get "/project_managers.xml?project_id=1", {}, @project_managers.to_xml
mock.get "/project_managers.xml?project_id=2", {}, [].to_xml
+ mock.put "/project_managers/6.xml", {}, nil, 204
end
class AssociationsTest < Test::Unit::TestCase
def setup
@project = Project.find(1)
- @project_manager = ProjectManager.find(5)
@other_project = Project.find(2)
+ @project_manager = ProjectManager.find(5)
+ @other_project_manager = ProjectManager.find(6)
end
#----------------------------------------------------------------------
@@ -46,5 +50,10 @@ def test_accessor_should_return_the_associated_project_manager
def test_accessor_should_return_nil_when_the_does_not_has_an_associated_resource
assert_nil @other_project.project_manager
end
+
+ def test_should_assign_a_new_project_manager
+ @other_project.project_manager = @other_project_manager
+ assert_equal @other_project.id, @other_project_manager.project_id
+ end
end

0 comments on commit af10377

Please sign in to comment.