使用javascript进行动态查询

时间:2015-05-19 13:03:06

标签: javascript ruby-on-rails

我目前正在编写一个简单的Ruby应用程序,它允许用户设置健身房位置首选项,以及可用性首选项 - 一周中的日期和上午/下午/晚上的布尔值。

用户索引视图

 <select id="myselect"></select>
 <script>
    queries = {
        'time': 'Afternoon',
        'day': 'Monday'
    }


    $.ajax({
        url: '/users.json',
        type: 'GET',
        data: {
            search: queries
        },
        dataType: 'json',
        success: function(json) {
            //console.debug(json)
            $.each(json.users, function(index, value) {
                $('#myselect').append($('<option>').text(value.name).attr('value', value.id));
            });
        }
    });
</script>

用户模型

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
has_many :places

def completed_profile?
%w( name email encrypted_password bio).all? { |attr| send(attr).present? }
end

def self.search(queries)
users = User.all

 if queries["time"]
   case queries["time"]
   when "Morning"
     users = users.where(morning: true)        
   when "Afternoon"
     users = users.where(afternoon: true)          
   end
 end
if queries["day"]
  case queries["day"]
  when "Monday"
    users = users.where(monday: true)
  end
end


users

end

end

在索引视图中设置动态javascript查询方面,有人能指出我正确的方向吗?我想让用户自己设置'查询'值,但我正在学习javascript,因为它一直很慢。

谢谢

1 个答案:

答案 0 :(得分:0)

替换以下方法

def self.search(queries)
  users = User.all

  if queries["time"]
   case queries["time"]
     when "Morning"
       users = users.where(morning: true)        
     when "Afternoon"
       users = users.where(afternoon: true)          
     end
  end
  if queries["day"]
    case queries["day"]
      when "Monday"
        users = users.where(monday: true)
      end
  end
  users
end

with,

def self.search(queries)  
  users = User.all
  if queries["time"]
    users = users.where("#{queries['time'].downcase} = ? ",true)
  end
  if queries["day"]
    users = users.where("#{queries['day'].downcase} = ? ",true)
  end
  users
end