【问题标题】:One month rails - pins_controller.rb (NameError in PinsController#new)一个月的 rails - pins_controller.rb (NameError in PinsController#new)
【发布时间】:2014-06-28 13:11:28
【问题描述】:

我正在学习 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 中的名称错误#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

用户.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

添加路由.rb

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

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

end

任何帮助将不胜感激!

【问题讨论】:

  • 你能发布你的模型吗?
  • User 模型中是否包含has_many :pins
  • 您可以发布您的routes.rb 文件吗?
  • 我添加了 routes.rb 文件...

标签: ruby-on-rails devise rubygems associations


【解决方案1】:

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

用户has_many 引脚和引脚belongs_to 用户。

【讨论】:

  • 如果只希望用户能够创建一个 pin,为什么不能使用 has_one?我有一个类似的错误并将我的 has_one 更改为 has_many,它现在可以工作了。
  • @Ken 您是否完整阅读了这些问题?他说has_many
【解决方案2】:

继承模型

该错误基本上表明 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

试试看是否有效

【讨论】:

    猜你喜欢
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    相关资源
    最近更新 更多