2013-02-14 71 views
2

这必须是一个容易的,但我卡... 所以我使用Rails#3与Mongoid,并希望动态生成查询,将取决于传递的参数和然后执行查找()。 喜欢的东西Mongoid动态查询

def select_posts 
    query = :all # pseudo-code here 
    if (params.has_key?(:author)) 
     query += where(:author => params[:author]) # this is pseudo-code again 
    end 

    if (params.has_key?(:post_date)) 
     query += where(:create_date => params[:post_date]) # stay with me 
    end 

    @post_bodies = [] 
    Post.find(query).each do |post| # last one 
     @post_bodies << post.body 
    end 

    respond_to do |format| 
     format.html 
     format.json { render :json => @post_bodies } 
    end 
end 

回答

5

您有几种不同的选择去与这里 - 根据您的实际应用中是如何复杂会得到什么。直接用你的例子 - 你可以用类似结束:

query = Post.all 
query = query.where(:author => params[:author]) if params.has_key?(:author) 
query = query.where(:create_date => params[:post_date]) if params.has_key?(:post_date) 
@post_bodies = query.map{|post| post.body} 

其中一期工程,因为Mongoid查询(标准)是可链接。


另外,如果你将有很多,你想利用更多的领域,你可以做到以下几点:

query = Post.all 
fields = {:author => :author, :post_date => :create_date} 
fields.each do |params_field, model_field| 
    query = query.where(model_field => params[params_field]) if params.has_key?(params_field) 
end 
@post_bodies = query.map{|post| post.body} 

最后,你可以把它一个级别进一步并正确地嵌套您的表单参数,并命名参数以使它们与您的模型匹配,以便您的对象看起来像这样:

params[:post] = {:author => "John Smith", :create_date => "1/1/1970", :another_field => "Lorem ipsum"} 

然后,你可以只是做:

@post_bodies = Post.where(params[:post]).map{|post| post.body} 

当然,与最后的例子,你要消毒输入字段 - 防止恶意用户使用行为的篡改。

+0

ok了,非常感谢你 – xaxa 2013-02-16 22:53:18

+0

嗨 我不喜欢这样 查询= '' PARAMS [:事件]。每做|键,值| query + =“{#{key}:#{value.to_s}},”if value.present? 结束 events = Event.or(查询) 但是在MONGOID中不工作...你能帮忙吗 – 2014-06-26 07:11:15