我有三种模式:文化,自然和历史。
我还有一个包含用户搜索标准的数组:
["nature", "culture", "history"]
当然,这个数组可能只包含一个或两个标准(例如"自然和文化"或只是"自然"等等)
根据这个数组,我想查询相应的模型并将结果呈现在一个唯一的集合中。
我尝试了很多东西,例如:
@sites = Culture.where(:coordinates => {"$ne" => "", "$ne" => nil} )
if array_type_sites.include?("nature")
@sitesNature = Nature.where(:coordinates => {"$ne" => "", "$ne" => nil} )
@sites << @sitesNature
end
if array_type_sites.include?("culture")
@sitesCulture = Culture.where(:coordinates => {"$ne" => "", "$ne" => nil} )
@sites << @sitesCulture
end
return @sites
在此代码中,@sites
未使用@sitesCulture
实施,仅适用于@sitesNature
。
让这项工作最好的方法是什么?
答案 0 :(得分:0)
你试过Mongoid中的继承吗? http://mongoid.org/en/mongoid/docs/documents.html#inheritance
以下测试执行我认为您想要做的事情,包括文化,历史和自然对象 存储和从保留类型的集合中获取。 我希望你觉得这很有用。
应用程序/模型/兴趣
class Interest
include Mongoid::Document
field :description, type: String
field :coordinates, type: String
end
应用程序/模型/文化
class Culture < Interest; end
应用程序/模型/历史
class History < Interest; end
应用程序/模型/性质
class Nature < Interest; end
测试/单元/ interest_test.rb
require 'test_helper'
require 'pp'
class InterestTest < ActiveSupport::TestCase
def setup
Interest.delete_all
Culture.delete_all
History.delete_all
Nature.delete_all
end
test "version" do
puts "\nMongoid::VERSION:#{Mongoid::VERSION}\nMoped::VERSION:#{Moped::VERSION}"
end
test "inheritance" do
Culture.create(description: "a culture site", coordinates: "40.7577° N, 73.9857° W")
History.create(description: "a history site", coordinates: "40.7577° N, 73.9857° W")
Nature.create(description: "a nature site", coordinates: "40.7577° N, 73.9857° W")
array_type_sites = ["nature", "culture", "history"]
@sites = Culture.where(:coordinates => {"$ne" => "", "$ne" => nil} ).to_a
if array_type_sites.include?("nature")
@sitesNature = Nature.where(:coordinates => {"$ne" => "", "$ne" => nil} ).to_a
@sites += @sitesNature
end
if array_type_sites.include?("culture")
@sitesCulture = Culture.where(:coordinates => {"$ne" => "", "$ne" => nil} ).to_a
@sites += @sitesCulture
end
Interest.collection.insert(@sites.collect{|site|site.serializable_hash})
puts
pp Interest.all.to_a
end
end
rake test
Run options:
# Running tests:
[1/2] InterestTest#test_inheritance
[#<Culture _id: 53dfd43b7f11ba43ef000001, description: "a culture site", coordinates: "40.7577° N, 73.9857° W", _type: "Culture">,
#<History _id: 53dfd43b7f11ba43ef000002, description: "a history site", coordinates: "40.7577° N, 73.9857° W", _type: "History">,
#<Nature _id: 53dfd43b7f11ba43ef000003, description: "a nature site", coordinates: "40.7577° N, 73.9857° W", _type: "Nature">]
[2/2] InterestTest#test_version
Mongoid::VERSION:3.1.6
Moped::VERSION:1.5.2
Finished tests in 0.084751s, 23.5985 tests/s, 0.0000 assertions/s.
2 tests, 0 assertions, 0 failures, 0 errors, 0 skips
ruby -v: ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin12.0]