2

I'm probably doing something stupid, but...

app/model/user.rb:

class User < ActiveRecord::Base
has_one :totem

config/routes.rb:

resources :users do
    resource :totem
end

app/controllers/totems_controller.rb:

class TotemsController < ApplicationController

    before_filter do
        @user = User.find(params[:user_id])
    end

    def new
        @totem = @user.build_totem
    end

end

app/views/totems/new.html.erb:

<%= form_for [@user, @totem] do |f| %>
<% end %>

Then, when I navigate to /users/123/totem/new, I get the error:

ActionView::Template::Error (undefined method `user_totems_path' for #<#<Class:0x007f9d3c843b00>:0x007f9d3bb6dd68>):

But because I'm using resource :totem instead of resources :totems in routes.rb, the path helper it should be using is user_totem_path. Why isn't it trying to use the correct path helper?

aidan
  • 9,310
  • 8
  • 68
  • 82
  • possible duplicate of [Ruby on rails: singular resource and form\_for](http://stackoverflow.com/questions/3736759/ruby-on-rails-singular-resource-and-form-for) – aidan May 31 '13 at 05:22

4 Answers4

6

Found my answer in another question: Ruby on rails: singular resource and form_for

app/models/totem.rb:

class Totem < ActiveRecord::Base
    model_name.instance_variable_set :@route_key, 'totem'
    belongs_to :user
end

(not sure why this Q&A didn't appear in my earlier searches...)

Community
  • 1
  • 1
aidan
  • 9,310
  • 8
  • 68
  • 82
1

Or you could just use

form_for @totem, :url => user_totem_path(@user) do |f|
0

instead of

resource :totem

it should be

resources :totem 
logesh
  • 2,572
  • 4
  • 33
  • 60
sp1rs
  • 786
  • 8
  • 23
  • 2
    I was using `resources` before, but I'd prefer to use `resource` because each user has only one totem, and `resource` generates slightly neater URLs. – aidan May 31 '13 at 04:37
0

I couldn't figure out why too. I used this way (providing a url to form_for) to bypass the problem

<%= form_for [@user, @totem], :as => :totem, :url => user_totem_path do |f| %>

Also, some research from google find out that there's a bug report in earlier rails. But i am not sure whether it's been fixed or not in the latest rails. Here is the link if you would like to do more research

https://rails.lighthouseapp.com/projects/8994/tickets/267

Henry
  • 1,047
  • 9
  • 8