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)

2 Answers 2

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])
Sign up to request clarification or add additional context in comments.

3 Comments

i'd like the siteId to be the only condition. when i try: @inventories = Inventory.find(:all, :conditions => ["siteId=?", params[:siteId]]) the error persists.
@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
yes james, i'm so sorry. it was in rendering the xml after executing this query.
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}"}

1 Comment

this might be a noob question, but I'm trying to query all inventories with siteId = 17.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.