我需要获取某个对象的 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_accessible
或 attr_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/