5

I have a nested ActiveResource model (i.e. it's within another model's namespace). Trying to call save raises:

ActiveResource::MissingPrefixParam: client_id prefix_option is missing

How do I supply the needed prefix?

Here's my class:

class Foo::Bar < ActiveResource::Base
  self.site = "http://www.example.com"
  self.prefix = "/clients/:client_id"
  self.element_name = "policy"
  self.collection_name = "policies"
end

Here's my save attempt:

bar = Foo::Bar.new :client_id => 123
bar.valid? # => true
bar.client_id # => 123
bar.save # => ActiveResource::MissingPrefixParam...

Time and again I've looked for elucidation on this, but I only find the same instruction:

When a GET is requested for a nested resource and you don’t provide the prefix_param an ActiveResource::MissingPrefixParam will be raised.

I'm trying to access our server's API endpoint at http://www.example.com/clients/[client_id]/policies, but I'm apparently failing to supply client_id, so my app makes its request to http://www.example.com/clients//policies

The server log tells me: ActionController::RoutingError (No route matches "/clients//policies/" with {:method=>:post}).

user229044
  • 232,980
  • 40
  • 330
  • 338
JellicleCat
  • 28,480
  • 24
  • 109
  • 162

2 Answers2

6

It will work if you create a method prefix_options, which supplies a Hash containing the needed client_id prefix_option, like so:

def prefix_options
  { :client_id => client_id }
end
JellicleCat
  • 28,480
  • 24
  • 109
  • 162
-1

I am assuming you want to create a new policy for a particular client. The path to which you should post your policy details should be:

client_policies_path(@client.id)

If you are using a form, you can use form_for like this:

form_for [@client, @policy] do

where @client and @policy are created by the #new action in your PolicyController like this:

def new
  @client = Client.new(params[:client_id])
  @policy = @client.policies.build
  # ...
end
Salil
  • 9,534
  • 9
  • 42
  • 56
  • Thanks, but it doesn't work. (I can't see how it would work, but I tried it all anyway). 1) There's no `client_policies_path` (I'm using `ActiveResource`, not `ActiveRecord`, so the route doesn't exist in my routes file; it's specified in the Model). 2) I'm not using a form (I'm using console), and setting controller attributes `@policy` and `@client` have no bearing on the outcome. I'm using `ActiveResource` and merely calling `save` on the instance. The policy instance in question already knows its own `:client_id`. -- Am I misunderstanding your answer? – JellicleCat Jun 05 '12 at 15:53