【问题标题】:rails 3 - path error when using form_for on a resourcerails 3 - 在资源上使用 form_for 时出现路径错误
【发布时间】:2012-06-11 23:12:58
【问题描述】:

在我的 rails 项目中,当我查看 /subscription/new 时出现以下错误:

NoMethodError in Subscriptions#new

Showing /redacted/app/views/subscriptions/new.html.erb where line #4 raised:

undefined method `subscriptions_path' for #<#<Class:0x007fd02c8bbb28>:0x007fd0308f7a48>

Extracted source (around line #4):

1: <div class="grid_6">
2:   <h1>New Subscription</h1>
3:   <p>
4:     <%= form_for @subscription, :html => { class: 'form_dark' } do |f| %>
5:       <% if @subscription.errors.any? %>
6:         <div class="error_messages">
7:           <h1><%= pluralize(@subscription.errors.count, "error") %> prohibited this subscription from being saved:</h1>

我的路线文件为此包含resource :subscription

附加代码信息:

用户模型:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_one :subscription
end

订阅模式:

class Subscription < ActiveRecord::Base
  attr_accessible :status, :stripe_token, :user_id, :last_charge, :stripe_card_token
  belongs_to :user
  has_many :payments, :dependent => :destroy
  belongs_to :plan
  attr_accessor :stripe_card_token
end

我的 SubscriptionsController 新方法:

def new
    @subscription = User.find(current_user.id).build_subscription 
end

感谢任何帮助,谢谢!

【问题讨论】:

  • 你指的是 SessionsController 还是 SubscriptionsController?
  • @cdesrosiers 嘿,对不起,我的意思是 SubscriptionsController - 一定有过会议。已修复,谢谢。

标签: ruby-on-rails ruby path routes


【解决方案1】:

我相信,当您传递 form_for 像 @subscription (具有 Subscription 类)这样的对象时,默认情况下它需要 url subscriptions_path。但是由于您已将订阅声明为单一资源,因此将定义 url subscription_path。你应该明确指定这条路线

<%= form_for @subscription, url: subscription_path, :html => { class: 'form_dark' } do |f| %>

【讨论】:

  • 谢谢!这确实解决了问题。
  • 我相信当您在路由文件中嵌套资源时也会发生这种情况。内部资源定义为单数(rails6)
【解决方案2】:

两个政治可疑点,

1. 您的应用中没有订阅控制器
2. 你有没有在你应用的路由文件中定义subscriptions_path自定义路由?

在阅读了您的评论和更正后,我们只剩下路线问题了

【讨论】:

  • 抱歉,忽略 SessionsController 位(已修复),我的意思是输入 SubscriptionsController。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多