buddhamagnet
buddhamagnet

Reputation: 230

singleton resource and controllers in rails 3

I am trying to set up a singleton resource and I may had had too much coffee. Here's the deal. All appropriate scaffolds have been created and I have this in the routes file:

resources :users do
  resource :hat
end

...based on a user has_one :hat and a hat belongs_to :user.

Have run rake routes and can see all the correct RESTful routes but when I go to, for example, /users/2/hat, the controller borks and tells me it cannot find a hat without an ID. I was under the impression that a singleton resource by its very nature negates a need for an ID in the finder as it is a single resource.

Any ideas or is it the coffee?

Upvotes: 0

Views: 2286

Answers (1)

Ernest
Ernest

Reputation: 8829

Well you do have two choices. If you really think that :hat deserves a separate resource (and just having belongs_to relation doesn't imply that), then I just hope you haven't forgotten about creating HatController.

On a second hand you may be just happy with extra member route:

  resources :users do
    match :hat, :via => [:get, :post], :on => :member
  end

In this case you need a "hat" action in UsersController.

A little bit more of your code would be helpful.

EDIT

I just tested it myself, and assumption is correct, and it works:

>curl http://localhost:3000/users/1/hat
<!DOCTYPE html>
<html>
<head>
  <title>Utest</title>
  <link href="/stylesheets/scaffold.css?1304678667" media="screen" rel="stylesheet" type="text/css" />
  <script src="/javascripts/prototype.js?1304678590" type="text/javascript"></script>
<script src="/javascripts/effects.js?1304678590" type="text/javascript"></script>
<script src="/javascripts/dragdrop.js?1304678590" type="text/javascript"></script>
<script src="/javascripts/controls.js?1304678590" type="text/javascript"></script>
<script src="/javascripts/rails.js?1304678590" type="text/javascript"></script>
<script src="/javascripts/application.js?1304678590" type="text/javascript"></script>
  <meta name="csrf-param" content="authenticity_token"/>
<meta name="csrf-token" content="6RvaQqHxYGFih2vh+3UmHJnqYPfVh/dqdpkLwva6Yko="/>
</head>
<body>

HatController#Show

<a href="/users/1/hat">Self</a>

</body>
</html>

In my case I've just had to force singular form for controller, but that is probably my mistake somewhere:

  resources :users do 
    resource :hat, :controller => :hat
  end

Upvotes: 2

Related Questions