rails 3 - 在资源上使用form_for时出现路径错误

时间:2012-06-07 20:46:01

标签: ruby-on-rails ruby path routes

在我的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

感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:0)

两个政治上可疑的地方,

1.您的应用中没有订阅控制器
 2.您是否在应用程序的路径文件中定义了subscriptions_path自定义路线?

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