简体   繁体   中英

Rails model returning nil ID

I need to get the id of a certain object. It's probably something really simple that I am missing. The object I need comes out from the database, and I'm able to retrieve its attributes but not the 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"

This is the model:

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

I suppose it's something related to attr_accessible or attr_accessor , I tried to fiddle with them but nothing so I ask for help.

EDIT: asking for a reload returns an error in any way i try i get the object(where or 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

Also, the parts table is already populated, but here is the code that creates an entry:

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

This code is executed in another part of the code is not just before where I try to get the ID.

Restart your machine. I know it doesn't sound logical. I encountered a problem where I had two objects of the same class and the first/last method returned the last object. Restarting worked for me. (rails 3.1.1, ruby 1.9.2p320 (2012-04-20 revision 35421) [i686-linux]) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM