【发布时间】:2016-08-04 12:46:12
【问题描述】:
在控制台中我收到此错误:
peegin.user
NameError: undefined local variable or method `peegin' for main:Object
Did you mean? @peegin
另外,当我尝试在控制台中访问 Peegin 时,它不显示 user_id:
Peegin
=> Peegin(id: integer, title: string, meaning: string, example: string, created_at: datetime, updated_at: datetime, permalink: string)
2.3.0 :039 >
用户类
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 :peegins
end
Peegin 类
class Peegin < ActiveRecord::Base
belongs_to :user
before_create :generate_permalink
def to_param
permalink
end
private
def generate_permalink
pattern=self.title.parameterize
duplicates = Peegin.where(permalink: pattern)
if duplicates.present?
self.permalink = "#{pattern}-#{duplicates.count+1}"
else
self.permalink = self.title.parameterize
end
end
end
架构
ActiveRecord::Schema.define(version: 20160804115242) do
create_table "peegins", force: :cascade do |t|
t.string "title"
t.string "meaning"
t.string "example"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "permalink"
t.integer "user_id"
end
add_index "peegins", ["user_id"], name: "index_peegins_on_user_id", unique: true
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
【问题讨论】:
标签: mysql ruby-on-rails devise associations