我正在使用ruby 1.9.3和mysql 5.5开发Rails 3.2.9应用程序。我需要编写一个查询,其中我应该在我的控制器文件的where子句中使用用户定义的变量。这是代码..请让我知道我该怎么做!如果不是我怎么能转换对象(我猜是这样)我从代码行4号得到,以便我可以将它与fixnum进行比较
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
答案 0 :(得分:1)
您只需要在返回的对象上调用字段名称(列名称)。例如:
@no_of_licenses = Company.find(:first,:conditions => ["id = ?",@company_id] , :select => 'no_of_licenses').no_of_licenses
上述查询可简化为
@no_of_licenses = Company.where(:id => @company_id).pluck(:no_of_licenses).first
答案 1 :(得分:1)
@no_of_licenses = Company.find_by_sql("SELECT NO_OF_LICENSES FROM COMPANIES WHERE ID= #{@company_id}")
我认为这是......你想要的。