Reputation: 2849
Im working on a rails app where a user has the ability to upload photos. When a user uploads their photos it will appear on their profile. Everything works great besides when there is no photos created then I am unable to view the user profile page because of the photo being nil.
here is my show method in the users_controller.rb
def show
@user = User.find_by_id(:id)
@photo = @user.photos.find(params[:id])
end
Here is my show.html.erb
<% for photo in @user.photos %>
<%= photo.title %>
<%= photo.description %>
<%= image_tag photo.image_url(:thumbnail) %>
<%= link_to "Show", photo %>
<br>
<% end %>
How can I bypass this error?
Upvotes: 0
Views: 171
Reputation: 47971
You can replace the code in your show.html.erb
with this:
<% if @user.photos %>
<% for photo in @user.photos %>
<%= photo.title %>
<%= photo.description %>
<%= image_tag photo.image_url(:thumbnail) %>
<%= link_to "Show", photo %>
<br>
<% end %>
<% end %>
The problem is, when the user doesn't have any photos, @user.photos
returns nil
so you have to check for that first.
Upvotes: 1
Reputation: 107728
The code for your action seems wrong...
It should be this:
def show
@user = User.find(params[:id])
#@photo = @user.photos.find(params[:id])
end
I commented out the third line on purpose, because I'm not sure what it is you want to do there, yet.
The @user
variable needs to be defined using params[:id]
, given that this is the show
action for the UsersController
, so the id for the user will be passed through as params[:id]
.
But then you go and use this to find the photo for the user, which is what confuses me... the Photo
record's id
attribute is probably not going to be the same as the User
record's id
attribute.
So what is it?
Upvotes: 1