user1738017
user1738017

Reputation: 627

Using a variable as a column name in rails

I'm trying to set up two environments for my site, one on a development server, one on a live one. And I want to dictate which records from the DB can be seen on each server. I've created a file in my includes, for development it has this @show = "dev" and for live it has @show = "live" I've included this at the top of my application layout so it is on every page. Then in my views, with each database call I want to put some conditions like this:

- f = Event.find(:all, :conditions => ["#{@show} = 1"])

But it doesn't pick up @show as being the variable, just uses it explicitly or ignores it. Is there a simple way to do this or will this not work how I expect it to?

update

I've managed to make it work, but I have to include the file on each individual view rather than just on the application layout... Not ideal but it's a solution:

= render "includes/dev_live"

- f = Event.find(:all, :conditions => {@show => 1})

Upvotes: 0

Views: 1150

Answers (2)

Slicedpan
Slicedpan

Reputation: 5015

I think you would be better off changing your variables to symbols i.e

@show = :dev
@show = :live

then your active record query could become:

f = Event.find(:all, :conditions => {@show => 1})

Upvotes: 1

Amitkumar Jha
Amitkumar Jha

Reputation: 1333

you need to convert a Variable into instance variable. for using it in conditions.

You can try this

f = Event.find(:all, :conditions => {@show.to_sym => 1 })

Upvotes: 0

Related Questions