新手问题 我给 admin 添加了一个 name 的字段,但是访问 @admin.name 的时候报错

1272729223 · 2012年08月09日 · 最后由 1272729223 回复于 2012年08月09日 · 3065 次阅读

是不是哪里还有没有添加的?

Banlab  rails c
Loading development environment (Rails 3.2.6)
1.9.3-p194 :001 > Admin.column_names
 => ["id", "email", "encrypted_password", "reset_password_token", "reset_password_sent_at", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "created_at", "updated_at", "name"] 
1.9.3-p194 :002 > 
class Admin < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :name
  # attr_accessible :title, :body
end
p#notice
  = notice

article
  header
    h1 = @blog.title
    = timeago_tag @blog.created_at, nojs:true, limit:10.days.ago, class:"post_at_time"
    span created_by #{@admin.name}
  = simple_format(@blog.content)
  - if admin_signed_in?
    footer.nav
      ul.group
        li.group
          = link_to 'Edit', edit_blog_path(@blog)
        li.group
          = link_to 'Destroy', @blog, method: :delete, data: {confirm:"I'm Really Sure?"}
        li.group
          = link_to "Cancel", blogs_path

 NoMethodError in Blogs#show

Showing /Users/yuwen/Documents/bitbucket/Banlab/app/views/blogs/show.html.slim where line #8 raised:

undefined method `name' for nil:NilClass

Extracted source (around line #8):

5:   header
6:     h1 = @blog.title
7:     = timeago_tag @blog.created_at, nojs:true, limit:10.days.ago, class:"post_at_time"
8:     span Created by #{@admin.name}
9:   = simple_format(@blog.content)
10:   - if admin_signed_in?
11:     footer.nav

我觉得是你看错误消息看的不仔细,关键在这里:

undefined method `name' for nil:NilClass

#1 楼 @lgn21st 是的,我不知道这是什么意思,很抱歉啊 未定义的方法?

#4 楼 @1272729223 #3 楼@Rei 正解,你在 view 中取得的@admin 对象是个 nil,不是一个 user 的 instance.

#5 楼 @lgn21st 恩 我还在弄怎么回事 谢谢。先吃饭去了 呵呵 :)

我的 blog 里面有这些字段:

1.9.3-p194 :002 > Blog.column_names
 => ["id", "title", "content", "created_at", "updated_at"] 
1.9.3-p194 :003 > 

是不是,我要显示这篇文章由谁发布,应该在 blog 表里面添加一个 user 的字段?还是我直接调用 users 里面的用户?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号