find syntax problem noob problem

Hi,

I need to know why

<%= SglineItem.find(1).sguser_id %>

works but

  <%= SglineItem.find(:all, :conditions => "sguser_id = #{params[:id]}").sguser_id %>

does not. the second gives sguser_id is not valid.

try <%= SglineItem.find(:all, :conditions => [‘sguser_id =?’, params[:id] ] ).sguser_id %>

hope it will work…

:slight_smile: Bala

Still gives “undefined method `sguser_id' for #<Array:0xb6896af0>”

**From:**
rubyonrails-talk@googlegroups.com [mailto:rubyonrails-talk@googlegroups.com] **On
Behalf Of** bala kishore pulicherla

:o

try

<% sgitem = SglineItem.find(:all, :conditions => [‘sguser_id =?’, params[:id] ] ).sguser_id %> <% for item in sgitem %> <%= item %> <%end %>

because find(1) (or find :first, ... ) return a single record from the database. find :all, returns an array. that array does not have a sguser_id method (even if the things in it do).

Fred

Yeah this was what I thought. The finds are two different things. How do I get it to return a record instead of an array while looking for a value not in the :id coloumn Fedrick?

Yeah this was what I thought. The finds are two different things. How do I get it to return a record instead of an array while looking for a value not in the :id coloumn Fedrick?

use find :first instead of find :all (or just take the array and select the first item in it) (and of course you can use dynamic finders, find_by_xxx is analogous to find :first)

Fred

short form:

<%= params[:id] %>

:wink:

other than that:

<%= SglineItem.find(:first, :conditions => ["sguser_id = ?", params[:id]]).sguser_id %>

or

<%= SglineItem.find_by_sguser_id(params[:id]).sguser_id %>

you should be careful though because these queries could return nil if there's no record with the given id in the db. also, if you use conditions you should use the array syntax (like above) to prevent sql injection.

cheers

gerold