Find Conditions - Variable Column Name

Hi all.

I'm trying to DRY out a bit of code that I've written. Right now, its
something along the lines of:

if var="column1"
User.find(:all, :conditions =>{:column1=>true})
elsif var="column2"
User.find(:all, :conditions =>{:column2=>true})
...
end

Now, since I know that var is always going to represent a boolean
database column, is it possible to do something along the lines of

User.find(:all, :conditions => {:var =>true})

or am I stuck using the if statement?

Thanks in advance for your help :slight_smile:

Try it :slight_smile:

Fred

@user.send(var.to_sym)

@user.send(var.to_sym)

Thanks for the reply :slight_smile: Is there any way for me to alter a column value
accessed in such a way? When I try now, it gives errors on the = sign,
and I can't find anything similar that would allow me to do it.

You don't actually need the to_sym. As far as setting the value goes
you just need to call the appropriate method (ie "foo=")

Fred

Frederick Cheung wrote:

> @user.send(var.to_sym)

Thanks for the reply :slight_smile: �Is there any way for me to alter a column value
accessed in such a way? �When I try now, it gives errors on the = sign,
and I can't find anything similar that would allow me to do it.

You don't actually need the to_sym. As far as setting the value goes
you just need to call the appropriate method (ie "foo=")

Fred

I'm not sure I understand. I don't have a way to call anything like
that, because I'm storing the column name in a variable. If I use var =
value, that just changes the value of the variable var, and not the
column in the database. @user.send(var) = value causes errors, because
it returns the value, and not a variable set to the value, like
@user.column1 would return.

So basically, if var = "column1", how do I do something along the lines
of @user.var = value?

And I apologize if your last post did answer the question and I just
don't understand.

I'm not sure I understand. I don't have a way to call anything like
that, because I'm storing the column name in a variable. If I use var =
value, that just changes the value of the variable var, and not the
column in the database. @user.send(var) = value causes errors, because
it returns the value, and not a variable set to the value, like
@user.column1 would return.

So basically, if var = "column1", how do I do something along the lines
of @user.var = value?

The key bit of information is that @user.column = value is just
syntactic sugar for "call the method called 'column=' on @user, with
parameter value".
So @user.send(var+'=', 42) will call the appropriate method with the
appropriate value.

Fred

You are absolutely brilliant! Thanks very much for your help, its
working perfectly now :slight_smile: