Stuart Fellowes wrote:
I know this shouldn’t be in the view but to test the code it is.
Anyway if I do just session[user] I get back the user id (the id from
the user table)
which is good.
However this code does not work.
<% a = session[:user] %>
<% uname = User.find(:first, :conditions => id = a) %>
<%= @uname %>
TIA
Stuart
The first reply is indeed correct. That is not valid ruby syntax.
remember that anytime you see a => you are dealing with a hash. Hashes
have a key and a value. So what is the value of the :conditions key in
your hash? a string? another hash? It’s very unclear.
So the => must point to an object of some sort.
:conditions => “id = #{a}”
Would work, where #{a} is swapped out for whatever the value of a is.
However, for security reasons ActiveRecord support a better way.
:conditions => [“id = ?”, a]
Now the value of :conditions is an array, with the SQL fragment first,
and then a dynamic value. That value is inserted in the ? spot and
properly quoted so that noone can use SQL injection attacks on your
code.
Also, if you are running edge rails you can use a hash as the value.
:conditions => {:id => a}
Last, but not least, rails has a shortcut dynamic method to find a
record where an attribute equals something.
User.find_by_id(a)
User.find_all_by_status(“admin”)
A long answer to a simple question I suppose, but I hope it helps you
understand a little more about awesome ActiveRecord is.