一个月rails - pins_controller.rb(PinsController中的NameError #new)

时间:2014-06-28 13:11:29

标签: ruby-on-rails devise rubygems associations

我正在完成OMR课程,似乎无法调试此错误:

Started GET "/pins/new" for 127.0.0.1 at 2014-06-28 09:06:35 -0400
Processing by PinsController#new as HTML
User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 2  ORDER BY   "users"."id" ASC LIMIT 1
Completed 500 Internal Server Error in 7ms

NameError (uninitialized constant User::Pin):app/controllers/pins_controller.rb:15:in `new'


Rendered /Users/antonioortiz/.rvm/gems/ruby-2.0.0-p481/gems/actionpack  4.1.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.7ms)
Rendered /Users/antonioortiz/.rvm/gems/ruby-2.0.0-p481/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.6ms)
Rendered /Users/antonioortiz/.rvm/gems/ruby-2.0.0-p481/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)
Rendered /Users/antonioortiz/.rvm/gems/ruby-2.0.0-p481/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (18.1ms)

这是来自浏览器:     PinsController中的NameError #new     未初始化的常量User :: Pin

Extracted source (around line #15):

def new
  @pin = current_user.pins.build
end

def edit

添加模型

class Pin < ActiveRecord::Base
   belongs_to :user

   has_attached_file :image, styles => { :medium => "300x300>", :thumb => "100x100>"}
end

user.rb

class User < ActiveRecord::Base
   # Include default devise modules. Others available are:
   # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_many :pins
end

Addded routes.rb

Pinteresting::Application.routes.draw do
  resources :pins

  devise_for :users
  root "pages#home"
  get "about" => "pages#about"

end

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

确保在模型中正确设置关联。

用户has_many个图钉和图钉belongs_to用户。

答案 1 :(得分:0)

继承模型

该错误基本上表明Rails正在尝试查找一个继承的模型 - 如果你将它们命名为将会出现的类型:

#app/models/users/pin.rb
Class User::Pin < ActiveRecord::Base
   ...
end

这里的问题是你不想要这个;您想要访问Pin模型本身。

-

<强>解决方案

我认为问题在于您使用build

的方式

我不认为build会成为一个问题,但我想你会用它填充一个form_for对象。如果是这种情况,问题可能是Rails将尝试从您创建的对象中提取模型名称

问题是您的对象是作为关联关系构建的,这可能会导致Rails变得混乱。我想说测试更好的是:

#app/controllers/pins_controller.rb
Class PinsController < ApplicationController
   def new
      @pin = Pin.new #-> you can assign a user later
   end
end

试一试,看看它是否有效