Mocifile
Mocifile

Reputation: 587

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.

Upvotes: 2

Views: 2106

Answers (1)

Prasad Surase
Prasad Surase

Reputation: 6574

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]) )

Upvotes: 1

Related Questions