所以我刚刚完成了One Month Rails,在最后两个视频的某个地方,我在登录时停止了创建新的引脚。
当用户登录并尝试添加新图钉时会出现此问题。
这是我得到的错误:
NoMethodError in PinsController#create
undefined method `name' for #<Pin:0x41e0c08>
Extracted source (around line #22):
def create
@pin = current_user.pins.build(pin_params)
if @pin.save
redirect_to @pin, notice: 'Pin was successfully created.'
else
render action: 'new'
pins_controller.rb
class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@pins = Pin.all.order("created_at DESC").paginate(:page => params[:page], :per_page => 20)
end
def show
end
def new
@pin = current_user.pins.build
end
def edit
end
def create
@pin = current_user.pins.build(pin_params)
if @pin.save
redirect_to @pin, notice: 'Pin was successfully created.'
else
render action: 'new'
end
end
user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :pins, dependent: :destroy
validates :name, presence: true
validates :name, length: { minimum: 2 }
end
编辑所以我按照Doon的建议检查模型,并将其更改为:
user.rb
has_many :pins, dependent: :destroy
validates :name, presence: true
validates :name, length: { minimum: 2 }
pin.rb
validates :image, presence: true
validates :description, presence: true
这似乎消除了第一条错误消息,但现在我看到了一条新消息:
NameError in Pins#show
undefined local variable or method `pin' for #<#<Class:0x3e41920>:0x4e1bbe8>
来自show.html.erb
<% if current_user && pin.user == current_user %>
<%= link_to edit_pin_path(@pin) do %>
<span class="glyphicon glyphicon-pencil"></span>
Edit
<% end %>
<% end %>
帮助(再次)?
答案 0 :(得分:2)
您似乎正在name
模型中的某个位置访问字段Pin
但是name
表中的字段pins
或虚拟字段中不存在模型Pin
中的属性。这导致错误undefined method 'name' for #<Pin:0x41e0c08>
答案 1 :(得分:0)
如果查看db / schema.rb,您会看到那里没有名称字段。
但如果你看一下app / models / pin.rb
class Pin < ActiveRecord::Base
belongs_to :user
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
validates :image, presence: true
validates :description, presence: true
validates :name, length: { minimum: 2 }
end
您将看到一个验证:name,您可能错误地将其添加到该文件而不是user.rb.您无法验证不存在的字段。