Richa Sinha
Richa Sinha

Reputation: 1456

How to check if a column is present in a table?

I am using rails 2.3.2

I have a parameter in which i have a field name of a table. I want to find out whether or not the field is present in the table, to prevent sql injection.

User.find(:all, :group => params[:group], :conditions => { :admin => false })

I want to make sure that the params[:group] is a field from the table before actually executing the above query.

What is the way to find out that the given field is a valid field of the table?

Upvotes: 2

Views: 4531

Answers (2)

zwippie
zwippie

Reputation: 15515

You can use has_attribute?:

user = User.new
user.has_attribute?(params[:group])

Upvotes: 7

beugisma
beugisma

Reputation: 115

For instances you can use:

user.has_attribute?(params[:group])

For classes:

User.column_names.include?(params[:group])

But ActiveRecord's query-building methods like: where, group, order, and so on, are safe against SQL injection as long as you don't use raw SQL queries. o I wouldn't worry about it.

Upvotes: 4

Related Questions