0

我正在使用 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
4

2 回答 2

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
于 2013-05-30T08:38:10.047 回答
1
@no_of_licenses = Company.find_by_sql("SELECT NO_OF_LICENSES FROM COMPANIES WHERE ID= #{@company_id}")

我认为这是..你想要的。

于 2013-05-30T09:09:44.230 回答