2012-12-07 56 views
0

我有一个任务列出学生的细节。我想根据名字和城市进行搜索。如果cityId==0 and name='',那么我想列出我的所有学生的详细信息。我怎样才能做到这一点?我以错误的方式做到了这一点。控制器是:如果红宝石上的语句

if(Student.where(params[:cityId])==0) 
    studentcount = Student.count() 
    @students = Student.limit(params[:jtPageSize]).offset(params[:jtStartIndex]).order(params[:jtSorting]) 
    @jtable = {'Result' => 'OK','Records' => @students.map(&:attributes), :TotalRecordCount => studentcount} 
    else 
    studentcount = Student.where("name LIKE ? AND city = ?", "%#{params[:name]}%", params[:cityId]).count() 
    @students = Student.where("name LIKE ? AND city = ?", "%#{params[:name]}%", params[:cityId]).limit(params[:jtPageSize]).offset(params[:jtStartIndex]).order(params[:jtSorting]) 
    @jtable = {'Result' => 'OK','Records' => @students.map(&:attributes), :TotalRecordCount => studentcount} 
+1

需要注意的是,如果您使用的是Rails,则约定将命名为“city_id”而不是“cityID”。骆驼案例几乎只用于类名称。 – tadman

+0

控制器的代码太多,除了单行数据检索器和respond_to之外,移动到模型的所有内容。 – tokland

回答

1

你的情况应该是这样的:你有

if(Student.where(:cityId => params[:cityId]).count == 0) 

if语句测试一个ActiveRecord::Relation和平等的整数永远不会为真

+0

出现这样的错误,意外 ':' – Niths

+0

你正在使用红宝石1.8正确,那么你必须使用旧的hashrocket语法 - ':cityId => params [:cityId]' – krichard

+0

你可以安全地删除那些parens。是的,他们是在问题中,但他们绝对是单一的。 – tokland

0
if User.where(city_id: params[:cityId]).empty?