本文介绍了创建取决于参数动态查询在轨道3通过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能创造一些清洁出这个动态查询:
@photos = Photo.within(100:原点=> [PARAMS [:纬度],则params [:经度]),除非(PARAMS [:纬度] .nil? || PARAMS [:经度] .nil)?
如果@ photos.nil?然后
条件= String.new
值= Array.new
params.each_key做|关键|
如果key =='since_id',那么
条件<< 和,除非conditions.length == 0
条件<< ID>?
值<< PARAMS [关键]
ELSIF关键=='USER_ID',那么
条件<< 和,除非conditions.length == 0
条件<< USER_ID =?
值<< PARAMS [关键]
ELSIF关键=='身份证',那么
条件<< 和,除非conditions.length == 0
条件<< ID =?
值<< PARAMS [关键]
结束
结束
values.insert(0,条件)
@photos = Photo.limit(15).order(created_at DESC)。其中,(价值),除非values.nil?
结束
解决方案
我认为正确的方式来做到这一点是使用范围
范围:older_than,拉姆达{|价值|其中(ID>()?,value)如果值}
适用范围:with_id,拉姆达{|价值|其中,('ID =(?)',value)如果值}
适用范围:for_user,拉姆达{|价值|其中,('USER_ID =(?)',value)如果值}
在后面的搜索
@photos = Photo.within(100:原点=> [PARAMS [:纬度],则params [:经度])
除非(PARAMS [:纬度] .nil || PARAMS?[:东经] .nil?)
@photos = Photo.with_id(PARAMS [:ID])
.older_than(PARAMS [:since_id])
.for_user(PARAMS [:USER_ID])
.order(created_at DESC)
.limit(15)
Is it possible to create something cleaner out of this dynamic query:
@photos = Photo.within(100, :origin => [params[:latitude], params[:longitude]]) unless (params[:latitude].nil? || params[:longitude].nil?)
if @photos.nil? then
conditions = String.new
values = Array.new
params.each_key do |key|
if key == 'since_id' then
conditions << " AND " unless conditions.length == 0
conditions << "id > ?"
values << params[key]
elsif key == 'user_id' then
conditions << " AND " unless conditions.length == 0
conditions << "user_id = ?"
values << params[key]
elsif key == 'id' then
conditions << " AND " unless conditions.length == 0
conditions << "id = ?"
values << params[key]
end
end
values.insert(0, conditions)
@photos = Photo.limit(15).order("created_at DESC").where(values) unless values.nil?
end
解决方案
I think the right way to do it is use scopes
scope :older_than, lambda { |value| where('id > (?)', value) if value }
scope :with_id, lambda { |value| where('id = (?)', value) if value }
scope :for_user, lambda { |value| where('user_id = (?)', value) if value }
later in search
@photos = Photo.within(100, :origin => [params[:latitude], params[:longitude]])
unless (params[:latitude].nil? || params[:longitude].nil?)
@photos = Photo.with_id( params[ :id ] )
.older_than( params[ :since_id ] )
.for_user( params[ :user_id ] )
.order("created_at DESC")
.limit(15)
这篇关于创建取决于参数动态查询在轨道3通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!