0

I'm calling a rails app from another using ActiveResource. I need to supply the id of the new object to the first app (yes, controller create in this app knows how to handle receiving an id), so I do something like this:

a = ActiveResourceModel.new(:id => 1231231, :name => "test")
a.save

However, instead of doing POST to create a new resource it PUTs it, causing the receiving app to try to update the resource with id 1231231, which of course doesn't exist (I want to create it!), so I end up receiving a 404 error because of this.

Doing some testing the problem seems to be in ActiveResourceModel.new? which returns false, while ActiveResourceModel.exists? returns false too (Great, two methods which are supposed to be opposite return the same!).

diegogs
  • 2,036
  • 2
  • 16
  • 20

2 Answers2

2

Checking the AResource source and documentation, the new? method checks for the presence of the id and the exists? checks for the remote resource, making both returning the same.

Why exactly you need to pass the id to create a new object? Doesn't make sense. Anyway, You can try to call create method instead of save.

Lucas
  • 1,190
  • 8
  • 13
  • I forgot to add, create is the same as new+save. The id thing... The entities i will be creating are the same in both apps and need to be synchronized. Instead of having a mapping between the ids in each application we decided it would be easier to use uuids as ids and pass those around. – diegogs Feb 04 '10 at 16:51
  • create tries to post the resource directly. http://github.com/rails/rails/blob/master/activeresource/lib/active_resource/base.rb#L1327 You should avoid replication like that imho. a 3rd app to center the common data may be less problematic. – Lucas Feb 04 '10 at 17:01
1

I have the opposite problem. I EXPECT a PUT when calling AR.create with an id (since it implies the record already exists). However, with Rails 3.1 and up, it seems like the same code in Rails 3.0 that called PUT now in fact calls POST. Can anyone confirm this change? (Since I have control of the receiving server, I simply adjusted the POST code to have the same behavior as my old PUT code).

Chuck Han
  • 594
  • 1
  • 6
  • 12
  • Well, when in doubt, check the source code. In 3.0, create checks new? which looks to see if id.nil? In 3.1 and above, it also checks new?, but now, new? checks to see if the object has been persisted (which is different from checking to see if id is defined). So, to the original questioner, you'll get the behavior you are looking for (albeit quite late)... – Chuck Han Dec 18 '12 at 23:27