0

I'm using:

rails 2.3.9 ruby 1.9.3 windows 7 ultimate rubygems 1.8.24

This works:

@inventories = Inventory.find :first, :conditions => {:siteId => params[:siteId]}

This doesn't

@inventories = Inventory.find :all, :conditions => {:siteId => params[:siteId]}

Error message:

NoMethodError (undefined method `siteId' for #Array:0x49738f8)
zishe
  • 10,665
  • 12
  • 64
  • 103
Aldrin Dela Cruz
  • 205
  • 1
  • 4
  • 15

2 Answers2

1

For rails 2.x your syntax is slightly wrong If you want to find all records with certain conditions then try this example which uses multiple conditions

@inventories = Inventory.find(:all, :conditions => ["siteId=? and priority=?", params[:siteId], 3])
jamesc
  • 12,423
  • 15
  • 74
  • 113
  • i'd like the siteId to be the only condition. when i try: @inventories = Inventory.find(:all, :conditions => ["siteId=?", params[:siteId]]) the error persists. – Aldrin Dela Cruz Sep 06 '12 at 09:10
  • @AldrinDelaCruz I'm sure it did work. Perhaps the error is not on the find but on a line after the find. Post the full stack trace of your error from your development.log file – jamesc Sep 06 '12 at 14:57
  • yes james, i'm so sorry. it was in rendering the xml after executing this query. – Aldrin Dela Cruz Sep 07 '12 at 03:32
0

when you write

@inventories = Inventory.find :first, :conditions => {:siteId => params[:siteId]}

Above line give you a single (first) object of the Inventory depending on the default order which matched the given condition so you can use @inventories.siteId. However when no row matches the given condition it will return nil and in such case if you try to use @inventories.siteId it will throws an error undefined methodsiteId' for nil`

But when you write

@inventories = Inventory.find :all, :conditions => {:siteId => params[:siteId]}

Above line gives you an array of the objects of Inventory no matters if your query returns the 1 or more than 1 objects i.e. row and blank array i.e [] if now rows satisfies the condition. So, when you try to use @inventories.siteId, you are actually applying siteId on Array and not on the object of Inventory and it will throws an error undefined methodsiteId' for #Array`. However following will work properly

@inventories.each{|p| puts "#{p.siteId}"}
Salil
  • 46,566
  • 21
  • 122
  • 156