mongoid嵌入文档标准,不承认
问题描述:
这里的模型mongoid嵌入文档标准,不承认
class Scammer
include Mongoid::Document
field :email_used
field :phone_used
field :name_used
field :first_logged, type: DateTime
field :last_scam_attempt, type: DateTime
field :checked, type: Integer, default: 0
field :scams_count, type: Integer
field :common_commodity
field :status
embeds_many :reports
embeds_many :reporters
embeds_many :requestors
end
class Report
include Mongoid::Document
embedded_in :scammer
field :reported, type: DateTime
field :posed_as
field :encountered_through
field :commodity
field :details
field :logged_by
end
class Reporter
include Mongoid::Document
embedded_in :scammer
field :reporter_ip
field :captured, type: DateTime
end
class Requestor
include Mongoid::Document
embedded_in :scammer
field :requestor_ip
field :captured, type: DateTime
end
现在这里是我用来尝试做一些有这些模特
# It's an email address,
if Scammer.where(email_used: @search_term).exists?
if not Scammer.requestors.where(requestor_ip: request.remote_ip).exists?
Scammer.requestors.create(requestor_ip: request.remote_ip, captured: DateTime.current()).save
end
@return = Scammer.where(email_used: @search_term).to_json
else
# No entry found. We should now add this to the database as a search
@newscammer = Scammer.new(email_used: @search_term, checked: 1, first_logged: DateTime.current(), status: "Seems Legit")
@newscammer.requestors.create(requestor_ip: request.remote_ip, captured: DateTime.current())
@newscammer.save
@return = "{ 'message' : 'Email added to database' }"
end
一切正常,直到这行代码
Scammer.requestors.where(requestor_ip: request.remote_ip).exists?
此行会导致此错误
undefined method `requestors' for Scammer:Class
我已经通过Mongoid.org和各种其他帖子在这里和其他董事会,我无法找到一种方法来访问Scammers的嵌入式Requestor元素。我是Ruby的新手,并试图自己解决问题所需的尽职调查,但我很难过。
答
找到答案 - 模型没有错,它是控制器中的代码块。显然,一旦您使用
where
返回对象,您将失去搜索或使用其他函数(如where,find和find_by)的能力。
我重新写的代码块本身,而现在它的工作原理
if Scammer.where(email_used: search_term).exists? scammerRec = Scammer.find_by(email_used: search_term)
# Even though we found the parent object, we still need to use the .where function to pull the parent again and check for the requestor_ip in the requestors embedded doc
if not Scammer.where(email_used: search_term, "requestors.requestor_ip" => request.remote_ip).exists?
scammerRec.requestors.create(:requestor_ip => request.remote_ip)
end
returnjson = Scammer.where(email_used: search_term).to_json
else
# No entry found. We should now add this to the database as a search
newscammer = Scammer.new(email_used: search_term, checked: 1, first_logged: DateTime.current(), status: "Seems Legit")
requestor = Requestor.new
requestor.requestor_ip = request.remote_ip
Scammer.collection.update(newscammer.selector, {'$push' => {requestors: requestor.as_document}}, multi: true)
newscammer.save
returnjson = "{ 'message' : 'Email added to database' }"
end