Reputation: 193
I've been told that the find_by_path
method may be a better solution than where
I have this snippet in a migration file ...
prescriber_activity_request = InsightReportMenuItem.where(name: "Prescriber Activity With Patient").first
I'm new to rails. My question is, if I can use find_by_path
here, what does my path look like?
I guess I'm confused on how a database structures its paths.
Upvotes: 1
Views: 163
Reputation: 6942
It depends on what you need from the database. If you call .where, you will always get a non-nil result (if nothing is found that matches your condition it will be an empty array).
In your case, if nothing is found you'll get a nil error because calling .first on an empty array will error out.
If you're checking for the presence of a single record,
find_by_name('Prescriber Activity With Patient')
...is your find_by path. So you can do things like this
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
If you're using .where you can use .any? and then call .first if .any? returns true. Hope that helps. And for the record, you can do find_by_(any attribute in your InsightReportMenuItem table). For example:
InsightReportMenuItem.find_by_id(1)
will produce the first one in the table.
Upvotes: 1