0

I'm working on Rails 3.2.9 app with ruby 1.9.3 and mysql 5.5. I'm required to write a query where in i'm supposed to use a user defined variable in the where clause in my controller file. Here's the code.. Please let me know how can i do it! and if not how can i convert the object(i guess so) i get from code line no 4 so that i can compare it with a fixnum later

def is_user_allowed?
    @company_id = params[:user][:company_id]

    #THIS LINES GIVES A SYNTAX ERROR AT '?'
    @no_of_licenses = Company.find_by_sql("SELECT NO_OF_LICENSES FROM COMPANIES WHERE ID=?",@company_id)

    #THIS LINE RETURNS AN OBJECT I GUESS N HENCE CANNOT COMPARE WITH FIXNUM
    @no_of_licenses = Company.find(:first,:conditions => ["id = ?",@company_id] , :select => 'no_of_licenses')   

    @present_users = User.where("company_id = ?", @company_id).count

    if @present_users < @no_of_licenses
      return true
    else
      return false
    end
  end
Aks..
  • 1,343
  • 1
  • 20
  • 42

2 Answers2

1

You just have to call the field name(column name) on the returned object. For ex:

@no_of_licenses = Company.find(:first,:conditions => ["id = ?",@company_id] , :select => 'no_of_licenses').no_of_licenses

The above query can be simplified as

@no_of_licenses = Company.where(:id => @company_id).pluck(:no_of_licenses).first
Amit Thawait
  • 4,862
  • 2
  • 31
  • 25
1
@no_of_licenses = Company.find_by_sql("SELECT NO_OF_LICENSES FROM COMPANIES WHERE ID= #{@company_id}")

I think this is.. what u want.

Sonal S.
  • 1,444
  • 1
  • 15
  • 31
  • Well, I will not recommend this solution because @company_id is directly been taken from params as `@company_id = params[:user][:company_id]` . So, there is a possiblity of SQL Injection. – Amit Thawait May 30 '13 at 09:15
  • Company.select(:no_of_lincenses).where(:id => @company_id) U can use this also. It will work in rails 3.2.12 – Sonal S. May 30 '13 at 10:36