有人告诉我,这种find_by_path
方法可能比where
我在迁移文件中有这个片段......
prescriber_activity_request = InsightReportMenuItem.where(name: "Prescriber Activity With Patient").first
我是新来的铁路。我的问题是,如果我可以find_by_path
在这里使用,我的路径是什么样的?
我想我对数据库如何构建其路径感到困惑。
有人告诉我,这种find_by_path
方法可能比where
我在迁移文件中有这个片段......
prescriber_activity_request = InsightReportMenuItem.where(name: "Prescriber Activity With Patient").first
我是新来的铁路。我的问题是,如果我可以find_by_path
在这里使用,我的路径是什么样的?
我想我对数据库如何构建其路径感到困惑。
这取决于您需要从数据库中获得什么。如果您调用 .where,您将始终得到非零结果(如果没有找到与您的条件匹配的内容,它将是一个空数组)。
在您的情况下,如果没有找到任何内容,您将收到 nil 错误,因为在空数组上调用 .first 会出错。
如果您正在检查是否存在单个记录,
find_by_name('Prescriber Activity With Patient')
...是您的 find_by 路径。所以你可以做这样的事情
if @irmi = InsightReportMenuItem.find_by_name( "Prescriber Activity With Patient")
#redirect to insight_report_menu_item_path(@irmi) or whatever
else
#redirect_to root_path or whatever
end
如果您使用 .where 可以使用 .any?然后调用 .first if .any? 返回真。希望有帮助。为了记录,您可以执行 find_by_(您的 InsightReportMenuItem 表中的任何属性)。例如:
InsightReportMenuItem.find_by_id(1)
将产生表中的第一个。