Reputation: 3522
hi i am attempting to do a find_by_id, though when calling this method if the id doesnt exist im getting nil class
if current_user.admin?
@schedules = Schedule.all
elsif current_user.team_id?
@schedules = Schedule.find_by_team_id(current_user[:team_id])
end
error
NoMethodError in Schedules#index
Showing /Users//Sites/Rails/*/app/views/schedules/index.html.haml where line #44 raised:
undefined method `each' for nil:NilClass Extracted source (around line #44):
41: %th Location
42: %th{:style => "color: #675100;background: url(\"/img/sprites/alertboxes/bg-warning.png\") repeat-x #ffe68b;"} Manager
43: %tbody
44: - @schedules.each do |schedule|
45: %tr
46: %td= event_display(schedule.event)
47: %td
Upvotes: 0
Views: 243
Reputation: 1
The difference between finding an object by id and finding an object by attribute are:
Primary Key Finder Method (by ID)
@schedules = Schedule.find(<schedule_id>)
Result: Returns an object if found. Throws an error if not found.
Dynamic Finder Method (by any Attribute)
In this case you can find the object by looking up any of the attributes of the object.
@schedules = Schedule.find_by_team_id(<attribute_id>)
Result: Returns an object if found. Returns nil if not found.
If you do not wish to throw an error or just want to check if the object for a particular attribute exists, use the dynamic finder method.
Upvotes: 0
Reputation: 3522
This is the normal behaviour if you are using find_by_ will return nil if no record is found for that attribute. Also note that find_by_ returns only a record not an Enumerable. you should you where(...) or find_all_by_ instead
Upvotes: 1