ruby-on-rails - Rails 模型返回 nil ID

标签 ruby-on-rails ruby

我需要获取某个对象的 ID。这可能是我所缺少的非常简单的东西。我需要的对象来自数据库,我可以检索它的属性但不能检索 ID。

Part.where("code ='p8z68vprogen3'").first
# => <Part id: 486, code: "p8z68vprogen3", etc...>


Part.where("code ='p8z68vprogen3'").first.id
# => nil


Part.where("code ='p8z68vprogen3'").first.code
# => "p8z68vprogen3"

这是模型:

class Part < ActiveRecord::Base
  has_many :build_parts
  has_many :builds, :through => :build_parts
  belongs_to :category
  attr_accessible :code,:link,:description,:category_id
end

我想这是与 attr_accessibleattr_accessor 有关的东西,我试图摆弄它们但无济于事,所以我寻求帮助。

编辑: 要求重新加载以我尝试获取对象(where 或 find_by_)的任何方式返回错误

part_needed = Part.where("code ='p8z68vprogen3'").first
# => <Part id: 486, code: "p8z68vprogen3", etc..>

part_needed.reload
# ActiveRecord::RecordNotFound: Couldn't find Part without an ID

此外,零件表已经填充,但这里是创建条目的代码:

part = Part.new(
    :description => objs[1],
    :code => objs[2],
    :category_id => tips[objs[3].to_i]
)
part.save!

此代码在另一部分代码中执行,而不仅仅是在我尝试获取 ID 之前。

最佳答案

重新启动您的机器。我知道这听起来不合逻辑。我遇到了一个问题,我有两个同一个类的对象,第一个/最后一个方法返回了最后一个对象。重新启动对我有用。 (rails 3.1.1, ruby​​ 1.9.2p320 (2012-04-20 修订版 35421) [i686-linux]) )

关于ruby-on-rails - Rails 模型返回 nil ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12280603/

相关文章:

Ruby:为什么在 nil 类中定义实例变量?

ruby-on-rails - 没有路由匹配 { :controller= >"stocks", :action= >"create"} RSpec Rails 3

ruby-on-rails - Rails 检查参数键是否存在以及定义的值

javascript - Rails 和 React : TypeError: Cannot call method 'map' of undefined

javascript - Rails 和 ajax 文件上传 - 无法读取 null 错误的属性 'innerHTML'

ruby-on-rails - rails 将循环分成两个表。 rails View ,新手

ruby-on-rails - Gemfile组用于什么?

ruby - 我在哪里可以找到 Ruby 中的数学密集型应用程序

sql - 将数组放入 WHERE IN 子句 Ruby on Rails

ruby - Selenium Webdriver Chromedriver 在 headless 模式下启动超时