【问题标题】:form_for nested resource (singular) not using correct path helperform_for 嵌套资源(单数)未使用正确的路径助手
【发布时间】:2013-05-31 04:28:07
【问题描述】:

我可能在做一些愚蠢的事情,但是......

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 %>

然后,当我导航到 /users/123/totem/new 时,我收到错误:

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

但是因为我在 routes.rb 中使用 resource :totem 而不是 resources :totems,所以它应该使用的路径助手是 user_totem_path。为什么不尝试使用正确的路径助手?

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

在另一个问题中找到我的答案: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

(不知道为什么这个问答没有出现在我之前的搜索中……)

【讨论】:

    【解决方案2】:

    或者你可以使用

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

    【讨论】:

      【解决方案3】:

      而不是

      resource :totem
      

      应该是

      resources :totem 
      

      【讨论】:

      • 我之前使用resources,但我更喜欢使用resource,因为每个用户只有一个图腾,resource 生成的 URL 稍微整洁一些。
      【解决方案4】:

      我也不知道为什么。我用这种方式(提供form_for的url)来绕过问题

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

      此外,谷歌的一些研究发现在早期的 Rails 中有一个错误报告。但我不确定它是否在最新的导轨中得到修复。如果您想进行更多研究,请点击此处的链接

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-19
        • 2015-06-30
        • 2011-01-16
        • 1970-01-01
        • 2011-01-03
        • 1970-01-01
        相关资源
        最近更新 更多