RUBY - 找不到'id'= 1的用户

时间:2016-07-10 18:17:30

标签: ruby-on-rails ruby activerecord

我目前收到此错误:

  

MainController中的ActiveRecord :: RecordNotFound #index

我摧毁了一个由我自己保留的偏好。

  

错误:

     

MainController中的ActiveRecord :: RecordNotFound #index

     

找不到'id'= 1

的用户
def get_owner
    return User.find( self.owner );  // LINE WITH ERROR
end

以下是post.rb

class Post < ActiveRecord::Base
  enum status: [ :ps_normal, :ps_locked, :ps_blocked, :ps_protected ]
  enum sortable: [ :school, :company, :date ]

  validates :owner, presence: true

  def owner_name
    return self.get_owner.display_name;
  end

  def get_owner
    return User.find( self.owner );
  end

  def readable?
    return (self.status != :blocked ) ? true : false;
  end
end

更新#1

2.3.0 :001 > User.find(1)
User Load (1.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=1
    from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:324:in `raise_record_not_found_exception!'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:444:in `find_one'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:423:in `find_with_ids'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:71:in `find'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/querying.rb:3:in `find'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/core.rb:131:in `find'
    from (irb):1
    from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:110:in `start'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:9:in `start'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

我该如何解决这个问题?添加userid = 1?

更新#2

我在自己的用户名下删除了自己的偏好,但收到了此错误。人们说我缺少id = 1,但我不确定如何将其添加回数据库

1 个答案:

答案 0 :(得分:1)

根据您的控制台输出,没有id为1的用户。因此,如果您需要id=1的用户,您可以这样做。

首先,创建一个用户,其中包含与已删除用户相同的详细信息。用户成功创建后,转到Rails控制台并执行:

u = User.last
# => #<User id: x, ...... >
u.update_column(:id, 1)

有关详细信息,请参阅此处Rails API doc。根据您使用的Rails版本进行选择。